ArrayList vs Vector
which one do you prefer? and why?
ArrayList. It's more efficient, because it's not synchronised. (And synchronising an ArrayList is apparently still more efficient than using a Vector. The only reason one would possibly prefer a Vector is for writing applets which don't require plugins).
Similar Messages
-
Reading Individual Lines of Text Into An ArrayList or Vector From A File
I am trying to read each individual line of text of a .txt file into an ArrayList or Vector. I seem to get the same results no matter which Object I am using (ArrayList or Vector). The text file is a comma-delimited text file to be used as a database. I want to separate each line as an individual record then dump it into an ArrayList or Vector and have them loop through a StringTokenizer() class so that I can be sure each line has the correct number of fields before I commit it to a serialization file. Currently, the proper amount of records seems to be forming in the initial part of the program, I am just remiss at properly placing them in the Vector, or StringTokenizer classes so I can further manipulate them. I'm using the LineNumberReader class to get line numbers to use as record numbers and for loop indexes. I'm not sure (obviously) if this is a correct way to do it or not.
Any help is greatly appreciated in advance.
Thanks for all your time.
int n = 0;
try {
* read each individual line and count it as a separate record.
* place each record into an array or may be a string if it has 9 tokens
* if a record hasn't got 9 tokens, it isn't a record
* place each array or string into a Vector
in = new LineNumberReader(new FileReader(filename));
while ((record = in.readLine()) != null) {
n = in.getLineNumber();
rawData = new Vector();
for (int i = 0; i < n; i++) {
rawData.add(record);
if (record == null)
break;
*The following System.out.println() statement shows that all lines are correctly retrieved from the text file
*as separate records
System.out.println("Record No. " + n + "= " + record);
//Debug
/** When these print lines execute it reveals that only the last record has been inserted into the Vector as
* many times as I have records in the text file.
System.out.println("Number of Records = " + n);
System.out.println("VectorSize = " + rawData.size());
System.out.println("First rawDataElement = " + rawData.firstElement());
System.out.println("Second rawDataElement = " + rawData.get(1));
System.out.println("Third rawDataElement = " + rawData.get(2));
System.out.println("Fourth rawDataElement = " + rawData.lastElement());
* Next run each record through a StringTokenizer to be sure that there the correct number of fields present
* If it contains the correct number of fields, dump it into an alternate ArrayList or Vector.
* As it is now, the StringTokenizer gives a NullPointerException
for (int i = 0; i < n; i++) {
StringTokenizer recordSet = new StringTokenizer((String) table.get(n), ",");
while (recordSet.hasMoreTokens()) {
if (recordSet.countTokens() == 9) {
data = new Vector();
data.add((Object) recordSet.nextToken(","));
System.out.println("Vector data size = " + data.size());
System.out.println("Second dataElement = " + data.get(0));
System.out.println("String Tok recordSet = " + recordSet.countTokens()); System.out.println("Number of Records = " + n);
System.out.println("First dataElement = " + data.firstElement());
System.out.println("Second dataElement = " + data.get(0));
System.out.println("Third dataElement = " + data.get(2));
System.out.println("Fourth dataElement = " + data.lastElement());
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}I think your logic is broken.
rawData = new Vector();
creates a new instance of Vector for every record.
Your add() within a for loop adds the same record to the Vector n times. I think what you really want is something like this:in = new LineNumberReader(new FileReader(filename));
rawData = new Vector();
while ((record = in.readLine()) != null) {
n = in.getLineNumber();
rawData.add(record); Mark -
Method to return ArrayList or Vector doesn't work, why?
Hi, I try to return a ArrayList or Vector from a method but it does not work.. wondering why and how to fix it? Thanks:)
class Class1{
public static main(...){
Class2 test = new Class2();
ArrayList<String> resp = test.class2method(...);
if(resp.get(4).equals(...)) {
class Class2{
public ArrayList class2method(int NumInt1, int NumInt2, ...) {
ArrayList<String> arrayTesting = new ArrayList<String>(13);
responses.set(2, Integer.toString(NumInt1));
responses.set(3, Integer.toString(NumInt2));
responses.set(4, Integer.toString(NumInt3));
responses.set(5, Integer.toString(NumInt4));
responses.set(6, Integer.toString(NumInt5));
return responses;
}what is responses? don't you want to return
arrayTesting?yes, responses is arrayTesting, sorry did notmention
that.what do you mean? is the code you posted a typo or
what you actually have in your code?It's more than 1000 lines codes so I decided not to posted them but here is part of them. My point is that i tried to return a ArrayList or Vector even with a simple code, it does not work. Thanks for your help.
public class DemoScript {
public DemoScript() throws IOException {
// register the shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("close prog");
endApp();
public void endApp() {
System.out.println("done!");
System.exit(0);
public static void main(String[] args) {
Parameters p = new Parameters();
VMF vm = null;
//Elements: [0]time, [1]MsgType, [2]NumInt1, [3]NumInt2, [4]NumInt3, [5]NumInt4, [6]NumInt5, [7]NumLong,
// [8]String1, [9]String2, [10]String3, [11]String4, [12]String5
// ArrayList<String> responses = new ArrayList<String>(13);
try {
MyScript my = new MyScript();
if(args.length == 5) {
p.vmHost = args[1]; p.vmPort = Integer.parseInt(args[2]);
p.guiHost = args[3]; p.guiPort = Integer.parseInt(args[4]);
} else if(args.length == 4) {
p.vmHost = args[1]; p.vmPort = Integer.parseInt(args[2]); p.guiHost = args[3];
} else if(args.length == 3){
p.vmHost = args[1]; p.vmPort = Integer.parseInt(args[2]);
} else if(args.length == 2){
p.vmHost = args[1];
} else {
System.out.println("Usage: java MyScript [port #] [voice mail hostname] <voice mail socket #> <GUI hostname> <GUI socket #>");
System.out.println("Default: <voice mail socket #> = "+p.vmPort+", <GUI hostname> = "+p.guiHost+", <GUI socket #> = "+p.guiPort);
System.exit(-1);
// String hostname;
//int port;
/* Check for input arguments */
//if(args[0] != null){
// port = Integer.parseInt(args[0]);
// hostname = args[1];
//} else {
// port = 2000;
// hostname = "10.0.0.228";
//System.out.println("tews");
vm = new VMF(p.vmHost, p.vmPort, p.guiHost, p.guiPort);
vm.logon();
//vm.portAbort(4);/*
vm.portCapture(3, 0);
//vm.portAbort(4);/*
//vm.portOnhook();
//vm.portOffhook();
////vm.portStop(3); //to stop a port current operation
//vm.portWaitring(); //vm will not resp until port detects ring
//vm.portOffhook();
//vm.portGetdigits(5, 7);
//vm.portDialdigits("201");
//for(int i=0;i<100000000;i++);
//vm.portCallprogress(3, 0, 10);
//System.out.println("d");
//for(int i=0;i<1000000;i++);
//vm.portGetdigits(5, 7);
//vm.portRecordfile(30, 1, "\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
//vm.portClearDTMF();
//vm.portPlayfile("\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
//vm.portPlayprompt(2);
//vm.portSpeaknumber(3845);
//vm.portSpeakdigits("1639123478866478909");//75655656566657867867*");
//vm.portExternalcall(4, "933");
ArrayList<String> response = vm.portInternalcall(2, "201");
System.out.println(response.get(4));
if(response.get(4).equals("DONE")) {
vm.portPlayprompt(1); vm.portPlayprompt(2);
} else if(response.get(4).equals("GONE")) {
vm.portSpeakttsstring("hello. This will create ");//a project with all of the proper SWT and JFace imports. Version 4.1.1 latest build released (SWT visual inheritance, enhanced SWT GridLayout support, non-visual beans, custom !!!SWT widgets, code generation enhancements, expose property, etc.)");
vm.portRelease();
vm.logoff();
vm = new VMF(p.vmHost, p.vmPort, p.guiHost, p.guiPort);
vm.logon();
vm.portCapture(Integer.parseInt(args[0]), 0);
vm.portOnhook();
vm.portOffhook();
// vm.portGetdigits(5, 7);
//vm.portRecordfile(30, 1, "\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
//vm.portClearDTMF();
//vm.portPlayfile("\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
vm.portPlayprompt(86);
// vm.portSpeaknumber(3845);
//vm.portSpeakdigits("1639123478866478909");//75655656566657867867*");
//vm.portExternalcall(4, "933");
//vm.portInternalcall(9, "82045");
//vm.portSpeakttsstring("hello. This will create");// a project with all of the proper SWT and JFace imports. Version 4.1.1 latest build released (SWT visual inheritance, enhanced SWT GridLayout support, non-visual beans, custom !!!SWT widgets, code generation enhancements, expose property, etc.)");
vm.portRelease();
vm.logoff();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
//catch "STOP PORT"
vm.logoff();
class VMF {
public ArrayList<String> portInternalcall(int rings, String dial_string) {
if (logon_status == 0) {
System.err.println("Error: logon required");
logoff();closeAndExit();
} else if (capture_status == 0) {
System.err.println("Warning: portCapture required");logoff();closeAndExit();
} else if (rings <1 || rings >999 || !checkDigits(dial_string)) {
System.err.println("Warning: portInternalcall( [1-999] , \"[0-9,A-D,F,P,a-d,f,p,*,#]\" )");
breakString(dial_string);
ostruct.write("", "IVR", "123", 188, captured_port, rings, 0, 0, 0, 0, str1, str2, str3, str4, str5);
sendToGUI("s", "", "IVR", "123", "188", Integer.toString(captured_port),
Integer.toString(rings), "0", "0", "0", "0", str1, str2, str3, str4, str5);
readStream();
recToGUI("r", Integer.toString(MsgType),Integer.toString(NumInt1),Integer.toString(NumInt2),
Integer.toString(NumInt3),Integer.toString(NumInt4),Integer.toString(NumInt5),
Integer.toString(NumLong),String1,String2,String3,String4,String5);
responses.set(2, Integer.toString(NumInt1)); responses.set(3, Integer.toString(NumInt2));
responses.set(4, Integer.toString(NumInt3)); responses.set(5, Integer.toString(NumInt4));
responses.set(6, Integer.toString(NumInt5));
return responses;
} -
Should we use ArrayList or Vector?
Should we use ArrayList or Vector in web programming environment?
thanks,I used to use ArrayList everywhere since it was a newer class and recommended in books, but use Vector now because it is used in several key environments: Java 1 (Web browsers), Swing and J2ME. In Java2, Vector was retrofitted to use the Collections framework, so Vector implements List.
Anyway, you should probably deal with only the List interface anyway so whichever you decide will be localized. That way, if Sun suddenly stops supporting Vector, you will only need to make a change in one place.
List mylist = new Vector(); -
I'm writing an application that accept multiple connections.
To check the connections I have a thread that check these connections if they are in use, i iterate over these connections and if they are not used for a periode of time, i close this connection and remove them from my list and iterate further.
If i use a Vector to collect the connections, everything goes fine, but if i use a Arraylist, i get a concurrentmodificationexception, i now, this is normal, because the failfast of the iterator, so, i used the synchronize method of collections, but i got the same exception,
any suggestions to make ik work with an ArrayList.If i can make it work with a list i'me happy, i will try it with a linked list, thx
Heres the code of the methode
public void run() {
while (true) {
try {
Enumeration enum = null;
sleep(frequency);
long currTime = System.currentTimeMillis();
enum = TimeoutInputStream.instanceList.elements();
while (enum.hasMoreElements()) {
TimeoutInputStream stream =
(TimeoutInputStream) (enum.nextElement());
//ITERATOR FAILS HERE
long lastActive = stream.getLastActive(); System.out.println(".");
if (lastActive == 0) {
stream.setLastActive(currTime);
} else if ((currTime - lastActive) > timeout) {
stream.abort();
//HERE DO I REMOVE THE CONNECTION OUT OF THE LIST
System.out.println("Timeout: input stream aborted");
} catch (InterruptedException e) {
System.out.println(e); -
Performance of ArrayList with Vectors
Tell me any one that , is ArrayList Performance is Better then Vectors ? and if yes why so?
yes, again. As long as authors of introductory tests don't stop using Vector in their examples and Sun doesn't change the Swing method arguments to take a List instead of hardcoding a Vector (enabling people to finally abandong the thing without recoding every ListModel, TableModel, etc. they want to use) we'll keep seeing this.
Vector should be deprecated, in fact it should have been removed already (maybe with the name just becoming a wrapper for a synchronized ArrayList to maintain backwards compatibility for a few releases). -
How to display ArrayList of Vectors using Expression Language in a JSP
I have added all my values in a vector and this vector is then added to a List. How can I loop through this List, Vector and values in Vector using EL on JSP side. If you have any idea, pl. help with sample code.
Hi Kavita,
Well to display each employee information on jsp, you can use following code sceanarion.
<%
Iterator it= list.iterator();
while(it.hasnext()){
Employee emp=(Employee) it.next();
%>
<tr>
<td><%= emp.getName()%></td>// In the similar fashion you can display other attributes of employee in other td's.
</tr>
<%
}%>Hope this would be helpful to you.
Regards,
Gaurav Daga -
Evening,
Is there anything like a 2D Array in the ArrayList or Vector??Hi All.
I am translating soem code from C++ to JAVA.
in C++, I used vector< vector <int> > to create a sparse matrix / 2D array.
I know you can make a vector of vectors in JAVA but i have been unable to get the individual elements. For example. I have:
=========================
Vector matrix = new Vector();
for(){
Vector row = new Vector();
... Do some to initiate row so that it has size > 1...
matrix.add(row);
=========================
I can only do matrix.get(int), which gives me the entire row, but i can't do matrix.get(int).get(int) etc.... is there any way I can extract the[i] i,j element if a sparse matrix is set up this way or would i have to totally restructure?
Thanks -
Hello All,
I put the result from the database as a list of transfer objects ...is it better to use ArrayList or Vector to store them and use them in my action, jsp etc......I know using vector adds the synchronization overhead but someone advised that storing data in a vector is more advantageous...
Help is greatly appreciated...
Thanks,
maithri...
Message was edited by:
MaithriTypically, Vector is only recommended when your code needs to run in an older jvm, say version 1.2. Otherwords, array list is almost always recommended.
Even when you need synchronization, the ArrayList can become synchronized, and since you have to do that explicitly, a maintainer knows that you are doing operations that require synchronization, as opposed to using Vector, where you get synchronization whether you want it or not, so that doesn't tell the maintainer much.
- Adam -
Why Arraylist better than vector?
Hi,
Why Arraylist better than vector?.....i heared about it that fast then vector......how it's possible ?.....how can we find out....?ArrayList is faster then vector.because in vector class all the methods are synchronized.so it is obvoiusly slow.Not everything that appears obvious is actually true.
add more object into Arraylist and vector say(1000).we have a method called currentTimeMillis() in System class .
use that and try to iterate both (arraylist,vector) objectIf you had ever done this test (use 100000 rather than 1000 as the resolution of currentTimeMillis() is too course), then you would know that Vector is faster more often than not:new List() new List(N)
Add+Iterate Add+Iterate Add Only Iterate Only
ArList Vector ArList Vector ArList Vector ArList Vector
609 516 250 250 63 94 109 125
562 516 250 266 78 94 125 109
609 500 266 250 78 93 141 110
532 547 250 265 62 93 110 125
547 500 250 265 78 94 125 109
547 500 266 265 62 94 109 109
547 500 250 281 78 78 125 109
ms averaged over 7 runs:
565 511 255 263 71 91 121 114
jdk 1.4.2_07 Windows client
N = 1000000 The vector wins when you don't know the size it's going to end up (its capacity increases by 2 rather than 1.5 each time it grows, so there are fewer array allocations). There's no significant difference between the two on iteration. It is only when you are adding to a Vector that already has sufficient capacity that there's a measurable difference.
Anything that requires contension on the locks will probably adversely affect the Vector's performance.
Pete -
How can i read the text files and buffer the data in Vector?
hi. I have been running into this problem for days, but with no luck and losing right direction.
The problem is : I am trying to read a text file and buffer the data into a
Queue for each user.
the sample text file is as below:( 1st column is timestamp, 2nd is user_id, 3rd is packet_id, 4th is packet_seqno, 5th is packet_size)
0 1 1 1 512
1 2 1 2 512
2 3 1 3 512
3 4 1 4 512
4 5 1 5 512
5 6 1 6 512
6 7 1 7 512
7 8 1 8 512
8 9 1 9 512
9 10 1 10 512
10 1 2 11 512
11 2 2 12 512
12 3 2 13 512
13 4 2 14 512
14 5 2 15 512
15 6 2 16 512
16 7 2 17 512
17 8 2 18 512
18 9 2 19 512
19 10 2 20 512
20 1 3 21 512
21 2 3 22 512
22 3 3 23 512
23 4 3 24 512
24 5 3 25 512
25 6 3 26 512
26 7 3 27 512
27 8 3 28 512
28 9 3 29 512
29 10 3 30 512
30 1 4 31 512
31 2 4 32 512
32 3 4 33 512
33 4 4 34 512
34 5 4 35 512
35 6 4 36 512
36 7 4 37 512
37 8 4 38 512
38 9 4 39 512
39 10 4 40 512
40 1 5 41 512
41 2 5 42 512
42 3 5 43 512
43 4 5 44 512
44 5 5 45 512
45 6 5 46 512
46 7 5 47 512
47 8 5 48 512
48 9 5 49 512
49 10 5 50 512
50 1 6 51 512
51 2 6 52 512
52 3 6 53 512
53 4 6 54 512
54 5 6 55 512
55 6 6 56 512
56 7 6 57 512
57 8 6 58 512
58 9 6 59 512
59 10 6 60 512
60 1 7 61 512
61 2 7 62 512
62 3 7 63 512
63 4 7 64 512
64 5 7 65 512
65 6 7 66 512
66 7 7 67 512
67 8 7 68 512
68 9 7 69 512
69 10 7 70 512
70 1 8 71 512
71 2 8 72 512
What I wanna do is to read all the data above and buffer them in a queue for each user( there are only 10 users in total).
I already created a class called Class packet:
public class packet {
private int timestamp;
private int user_id;
private int packet_id;
private int packet_seqno;
private int packet_size;
/** Creates a new instance of packet */
public packet(int timestamp,int user_id, int packet_id,int packet_seqno, int packet_size)
this.timestamp = timestamp;
this.user_id=user_id;
this.packet_id=packet_id;
this.packet_seqno=packet_seqno;
this.packet_size=packet_size;
}then I wanna to create another Class called Class user which I can create a queue for each user (10 users in total) to store type packet information. the queue for each user will be in the order by timestamp.
any idea and sample code will be appreciated.Doesn't sound too hard to me. Your class User (the convention says to capitalize class names) will have an ArrayList or Vector in it to represent the queue, and a method to store a Packet object into the List. An array or ArrayList or Vector will hold the 10 user objects. You will find the right user object from packet.user_id and call the method.
Please try to write some code yourself. You won't learn anything from having someone else write it for you. Look at sample code using ArrayList and Vector, there's plenty out there. Post in the forum again if your code turns out not to behave. -
Scope of a non-static method printing a vector of objects
Hello everyone,
I'm new to using the java.util.Vector package. I wanted to create a print out of all the objects of class "Student" that I created within a "students" vector. My problem is that scope is causing a compile error when calling the print method acting on the students vector. Anybody got any ideas? Further to this I'd like to keep my printVec() generic enough so that I can create a class "Teachers" and a "teachers" array and make the the printVec() method able to print both, ie;
teachers.printVec()
students.printVec()My code is below;
import java.io.*;
import java.lang.*;
import java.util.*;
class Example {
public static void main(String[] args){
Vector<Student> students = new Vector<Student>();
students.addElement(new Student("Billy"));
students.addElement(new Student("Ryan"));
students.addElement(new Student("William"));
students.addElement(new Student("Jason"));
//the below print algorithm works...
for(int i=0;i<students.size();i++)
System.out.println(i+" "+students.elementAt(i).getName());
//however i can't get this following one to work...
// students.printVec();
//uncomment above line
public void printVec(){
// for(int i=0;i<students.size();i++)//uncomment these lines
// System.out.println(i+" "+students.elementAt(i).getName());//uncomment these lines
//uncomment above two lines
class Student{
//constructors
public Student(String name){
this.name = name;
this.subjectNumber = -1;
this.tutorialNumber = -1;
//methods
public String getName(){
return name;
//fields
private String name;
private int subjectNumber;
private int tutorialNumber;
}You should use an Iterator, not get(). And youshould
prefer ArrayList over Vector.Why are you telling me this? I know this already... I
was reusing the OP's way so that he/she/it could see
it done his/her/its way.I have no way of knowing what you do or don't know. I only saw crap code, so I corrected it.
>
That won't work if more than one student has thesame
name, and it's a very counterintuitive way to
approach the problem.Um... yes, it will work if more than one student has
the same name. It will not work if students in the
Vector share memory. It searches for memory, not the
name.Actually, we're both wrong.
If Student overrides equals to be based on name, then it won't work as I described. If not, then it will work.
It only looks at "memory" if Student does not override equals.
I didn't think that there would be a problem with
memory, but if there is, simply add a counter:????
What are you talking about?
public static void printVec(Vector<Student> students)
int count = 0;
for (Student s : students) {
System.out.println((count++) + " " +
+ " " + s.getName());
}That's the right way to do it, but that has nothing to do with "a problem with memory." -
Data base in to a Vector.
Hi folks,
I'm writing a program using JDBC with a data base that holds details of stock held by a company, my intention is to write a till system for it. I've got the JDBC part working now.
However I am left with one or two questions.
One of my initial ideas was to have another table called ShoppingList, but I felt that would be too much trouble, so my thought was to create a GUI with a grid of buttons, that would execute SELECT statements from the data base for the stock that it has stored within it, and add the output to a Vector of stock objects. (item quantity, item description, item price.)
I'm not sure that I'm making things over complicated in doing this or not. But i felt it would provide a better way for me to then yse the Quantity fields, and price fields, and make it easier to total up their numbers.
My intention is that the "shopping list" appears in a JTable, which to me presents another possible problem (I'm new to all this). I want to have a total cost of the shopping basket. My intention is to make this appear in a JTextArea at the bottom of the "list" Is it possible to have the sum of the values of a certain column in a seperate JTextArea? I know it sounds a dumb question, but I'm asking because I honestly don't know.
I know I've put a lot of questions on here, but please be patient with me. I'm learning slowly.
EmyrWell I gotta be honest with you here when someone says instead of a DBtable I would like to use a Vector/some GUI component it's a sign to me that their design is mixed up when it comes to seperating out the different components of their application.
There are basically three parts to your application
- the persistence storage level (the database)
- your business logic etc (Vectors or Lists)
- you interface (GUI)
Each one of these should be independent of the other.
Now. In reality when you are starting off this can seem overwhelming to think of it like this... but you really should. Or if you want to do just do as you like for now while you get the hang of a few things that okay too but you must keep in mind that in many ways it's so very wrong.
A couple of suggestions targeted at what you did post.
1) Write to interfaces and not implementations.
For example
List list = new Vector();and not
Vector list = new Vector();This will allow you to change the implementation later if needs be with a minimum of headache.
2) It is preferable to use another List implementation (like ArrayList) to Vector
3) How much do you know about TableModels (with JTables?)
4) The ShoppingList table sounds like a good idea to me. But it's hard to say what you are doing. The table should probably have a key based on the id of the shopper (or user) and the product id. -
Best efficiently way to transform a large rows ResultSet to Vector
Best efficiently way to transform a large rows ResultSet to a 2-dimensional ArrayList or Vector in a minute ?
If you can help me solve this problem , I 'll give you my duke .Why don't you use info objects? For example your table is having col1(number),col2(text/varchar),col3(text/varchar), create an info object like this,
class MytableInfo implements java.io.Serializable {
private int col1;
private String col2;
private String col3;
public MytableInfo(int col1,String col2,String col3) {
this.col1=col1;
this.col2=col2;
this.col3=col3;
public int getCol1() {
return col1;
//Getter for other two properties too.
and in your ResultSet class,
Vector v = new Vector();
while(rs.next()) v.add(new MytableInfo(rs.getInt(1),rs.getString(2),rs.getString(3));
return v;
So, it will be easier for retrieving the values later and it is a clean way of doing it.
Sudha -
If I wanna sort my arraylist, can I make it???How?
Thanx!Do you know how to use interfaces? Do you understand OOP and Java? Once nice thing about using generic types like an interface, is that you can easily switch out different algorithms. For example, if you are doing something like this:
ArrayList myList = new ArrayList();
and throughout your code you have methods like:
public void doSomething(ArrayList list)
you limit youself to using nothing but ArrayLists. What happens if your code suddenly is used by more than one concurrent person? You will no doubt run into mult-threading issues using an ArrayList. However, Vector, which is identical to an ArrayList but is thread-safe, can be swapped for an ArrayList with no changes to your code. You MUST use the methods defined in the interface however, when working on the ArrayList or Vector. As an example, there are times when you may want to "speed up" your code. When using a Vector, you lose a lot of speed because a Vector has a lot of syncronized overhead in it. This is to ensure that multiple threads do not lock or cause any problems while accessing the same Vector in memory. At times, you may find out that a certain Vector is NEVER accessed by more than one thread. Therefore, its a perfect candidate for turning into an ArrayList, as the ArrayList has no synchronized overhead and is thus much faster. But, if you are not using the List interface methods, you may find you need to change a lot more code for this to work.
List is an interface (java.util.List) that defines methods like add, remove, get, and so on. As the other replier said, you can use the Collection framework to sort a list, and do other things with it. If you use a Vector ad usee addElement(), removeElement, etc, they wont work with ArrayList or LinkedList. The List interface is implemented by ArrayList, Vector and LinkedList. Each has their benefits. For example, if you write a program using a Vector, and it does a LOT of moving items back and forth (such as sorting), a LinkedList will be faster because the way they work, they just move a pointer to move the entire contents of the list. A Vector and ArrayList have to copy the data. However, searching is done much faster on Vectors and ArrayLists. So if you need to do a lot of searching, then one of those two would be better. If you need to do all three (or more), then you need to experiment. The nice thing is, as long as you use the List interface everywhere (except when instantiating the objects), you can simply do a find/replace in your code to replace ArrayList with Vector or LinkedList and you are all set.
Hope that helps.
Maybe you are looking for
-
Announcement: Super 4.00 - a suite of EJB/J2EE monitoring/admin tools.
Announcement: Super 4.00 - a suite of EJB/J2EE monitoring/admin tools. Acelet is the leader in J2EE tools area. If you google "j2ee tools", "j2ee logging", "j2ee scheduler" or alike, you will find Acelet is at
-
How to get value of URL parameter
Hi, If an ABAP Web Dynpro URL looks like this: http://<server>:<port>/sap/bc/webdynpro/sap/zny_test1?sap-client=100&sap-language=EN, how to get value of the URL parameter sap-client at runtime in the application? Thanks, Nancy
-
Add Column name conditionally in a query
Hi i have an stored procedure where one parameter is passing @Type UserTable (columns) => username, canAdminDelete,canCustomerDelete,CanMerchantDelete i wants to add column conditionally like when usertype =1 then query should be like Select * from u
-
Hi everybody . I am using idoc with LSMW for uploading the data . I am going step by step all is working and displaying well but when i go for the step "START IDOC GENERATION " it is giving me an error like <b>'066_BUS_TRANS_QUOTATION.lsmw.conv' File
-
How do we implement "callback" mechanism in java. ? can any on eexplain me with an example?