LinkedList and ListIterator
Hello! I have been working on the following code and can get it to compile with no errors but cannot get the program to return the correct results.
When I have the ListIterator as hasPrevious() I get the following exception:
Exception in thread "main" java.util.NoSuchElementException at java.util.LinkedList$ListItr.previous(Unknown Source)
at LinkedListTest.main(LinkedListTest.java:29)
When I have the ListIterator as hasNext(), I get no return and the program gets "stuck" (like it cannot get out of the while loop).
I would like the ListIterator to start at the end of the list. Can someone take a look at the code and let me know what he/she thinks? I am very new to Java and am a little frustrated. (I apologize if this is posted incorrectly.)
Thanks in advance for any help-
Christle
import java.util.*;
import java.io.*;
public class LinkedListTest {
public static void main(String args[]) throws java.io.IOException {
BufferedReader bufRead = new BufferedReader (new InputStreamReader(System.in));
String inStr = null;
int foundN = 0;
LinkedList roster = new LinkedList();
roster.add("Bob");
roster.add("Tom");
roster.add("Jane");
System.out.println ("\nStudents in the list: \n" + roster.toString());
System.out.println("\nPlease enter a name to add at the beginning of the Linked List: ");
inStr = bufRead.readLine();
roster.addFirst(inStr);
System.out.println ("\nAfter adding " + inStr + " at the end: \n" + roster.toString());
System.out.println("\nPlease enter a name to find: ");
inStr = bufRead.readLine();
ListIterator listIter = roster.listIterator();
while (listIter.hasPrevious());
String aStrObj = (String) listIter.previous();
if (aStrObj.equals(inStr)){
foundN++;;
if (foundN > 0) {
System.out.println(inStr + " is found " + foundN + " time(s).");
else{
System.out.println(inStr + " is not found.");
}
hi 'Made in NZ',
sorry about that. I misunderstood your question. Yes, my code did not cater to wrong input i.e spaces or null. Now it is fixed. Cheers.
import java.util.*;
import java.io.*;
public class LinkedListTest {
public static void main(String args[]) {
LinkedListTest test = new LinkedListTest();
test.check();
public void check() {
BufferedReader bufRead = new BufferedReader (new InputStreamReader(System.in));
String inStr = null;
int foundN = 0;
LinkedList roster = new LinkedList();
roster.add("Bob");
roster.add("Tom");
roster.add("Jane");
System.out.println ("Students in the list: " + roster.toString());
System.out.println("Please enter a name to add at the beginning of the Linked List: ");
try {
inStr = bufRead.readLine();
while (inStr.trim().length() == 0 || inStr == null) {
System.out.println("Please enter a name");
inStr = bufRead.readLine();
roster.addFirst(inStr);
System.out.println ("After adding " + inStr + " at the end: " + roster.toString());
System.out.println("Please enter a name to find: ");
inStr = bufRead.readLine();
ListIterator listIter = roster.listIterator();
while (listIter.hasNext()) {
String aStrObj = (String) listIter.next();
if (aStrObj.equals(inStr)){
foundN++;;
catch (IOException ioe)
System.out.println("IOException occured");
if (foundN > 0) {
System.out.println(inStr + " is found " + foundN + " time(s).");
else{
System.out.println(inStr + " is not found.");
Similar Messages
-
I have seen some websites discussing about the performance of ArrayLists, LinkedLists, and Hashmaps:
http://forum.java.sun.com/thread.jspa?threadID=442985
http://java.sun.com/developer/JDCTechTips/2002/tt0910.html
http://www.javaspecialists.co.za/archive/Issue111.html
http://joust.kano.net/weblog/archives/000066.html
If I understand it right an ArrayList in general is faster for accessing a particular element in the collection and I can't find some pro's of using a LinkedList.
My question is: If I only use a large collection with more than 1 million elements for iterating from begin to end (i.e. for loop), is it faster to use a linked list or a custom linked list instead of an arraylist (or hashmap)? Since you can iterate "directly" through a (custom) linked list, which is not possible with a arraylist?
Edited by: 9squared on Nov 23, 2007 1:48 PMThanks for the help, I wrote some code and tested it
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
public class TestTemp {
public static void main(String[] args) {
List<Node> a = new ArrayList<Node>();
Node b = new Node("a");
String[] c = new String[10000000];
Node temp = b;
for (int i = 0; i < 10000000; i++)
a.add(new Node("a"));
temp.next = new Node("b");
temp = temp.next;
c[i] = "c";
long tstart;
tstart = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++)
c[i] = "cc";
if (i%200000 == 0)
System.out.println("Array " + i + ": " + (System.currentTimeMillis()-tstart));
tstart = System.currentTimeMillis();
temp = b;
for (int i = 0; i < 10000000; i++)
temp.next.text = "bb";
temp = temp.next;
if (i%200000 == 0)
System.out.println("LinkedList " + i + ": " + (System.currentTimeMillis()-tstart));
tstart = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++)
a.get(i).text = "aa";
if (i%200000 == 0)
System.out.println("ArrayList " + i + ": " + (System.currentTimeMillis()-tstart));
public class Node {
public String text;
public Node next;
public Node(String text)
this.text = text;
}Here are some results in milliseconds, and indeed just iterating doesn't take very long
Elements Linked Arraylist Array
200000 0 0 1
400000 5 13 5
600000 9 22 9
800000 14 32 12
1000000 20 42 16
1200000 25 52 19
1400000 31 63 23
1600000 37 72 26
1800000 42 82 30
2000000 47 92 33
2200000 51 101 37
2400000 56 112 40
2600000 60 123 44
2800000 65 134 47
3000000 69 143 51
3200000 73 152 55
3400000 78 162 59
3600000 84 175 63
3800000 103 185 67
4000000 108 195 70
4200000 113 207 74
4400000 117 216 78
4600000 122 225 81
4800000 127 237 85
5000000 131 247 88
5200000 136 256 92
5400000 142 266 97
5600000 147 275 101
5800000 153 286 107
6000000 159 298 113
6200000 162 307 117
6400000 167 317 121
6600000 171 326 125
6800000 175 335 128
7000000 180 346 132
7200000 184 358 136
7400000 188 368 139
7600000 193 377 143
7800000 197 388 147
8000000 201 397 150
8200000 207 410 154
8400000 212 423 157
8600000 217 432 162
8800000 222 442 167
9000000 227 452 171
9200000 231 462 175
9400000 236 473 178
9600000 242 483 182
9800000 249 495 185
10000000 257 505 189 -
LinkedList and ArrayList Iterator speeds
Is an ArrayList Iterator hugely faster than a LinkedList Iterator?
I have swapped, for storing my 8000 dataObjects, from using an ArrayList to a LinkedList and all seems fine except that the Iterator I get is much slower (by more than 10 times slower)
I have scoured my code but I have come to the conclusion that a LinkedList is just slow
Id just like one of you to comfirm my beliefsHow odd.
According to Bruce Eckel's Thinking in Java [p.505]
(downloadable for free at
http://www.mindview.net/Books/TIJ/ ), LinkedList
should be faster than ArrayList for iteration,
insertion, and removal; and only slower for getting by
index.
I haven't done any tests of my own on it, but it makes
sense. I don't know why your LinkedList iterators
would be slower.Yes, LinkedList will be faster at inserts/deletes and slower at indexed lookups. Keep in mind that when you say myLinkedList.get(7000) the iterator has to go through 6999 objects to retrieve the 7000th object. When you do the same thing on an ArrayList it just goes directly to that index and returns it. -
Help in Collections (LinkedList) and in Files I/O
Well, I've two questions, first one:
I'm trying to do a program which reads and writes (well, I'm only in the reading part :P) from/to Files with a kinda complex Layout (is it the word???) using java.io.*; it has the same limit of number of characters in every row, but it can be lower, and I don't know how to read them and store them in a String Array, specially an overloaded read() from my class where the paramters given are file, length in characters to read, and relative position in the layout... I kinda made a read() which reads ALL the text file... the first method returns a String[], but the last one returns String[][] (because I want to mantain the "layout")... What do you suggest me (well, at first try I was trying to use Data Bases but I really don't like the idea of basing my program in ANOTHER PROGRAM ... yes the one from Mycr0Zoft... I heard about making databases in Java is that true?, or I need that or any other program? Should I stay on the java.io.*???)
the second question:
When I Initialized the String[] and the String[][] to return in the read() methods I used an arbitrary (damn if that's not the word... I shouldn't have stopped studying the English language...!) size of [50]
in the rows, I really find disgusting that thing, and I managed to use LinkedList to store them, BUT ONLY in the String[], because I can add the individual String Objects to de LinkedList, to simulate a String[], but i can't use it on the String[][] case, cuz, as you may now, I can't add an Object[] to that collection...
Any Suggestions???
Thnx ...Yeah, I have a suggestion. Lay off the reefer.
Apart from that, perhaps BufferedReader would be helpful...it sounds like your input may be separated by newline into individual records (that is, each line is a logically separate bunch of data, pretty typical).
Using a List to hold each line seems fine, but if you find that you have a "layout" (and it's not at all clear what you're talking about when you say that) then perhaps you should define a class that encapsulates that layout, and maintain a List of those.
But don't worry about any of this until you come down. For now, listen to some Allman Brothers, and drink plenty of water. Stay at home; you don't want to be driving or trying to ride a bus right now. -
Switching between LinkedList and Array
Hi, I'm new to OOP and Java so please bear with me.
I've been given an assignment to code my own collection
similar to the Java Collection. It has to have sorted arrays,
unsorted arrays, sorted linked lists and unsorted linked lists.
Basically, the user has to be able to switch between an
array and a linked list if desired.
I have a variable that should only be set once and stays
constant even tho the user may switch between an array
and a linked list. So, say
constant variable x
List myList = new Array();
myList.set(x) = 10;
myList = new LinkedList();
In my current implementation, I am losing the value of x
after I switch to a linked list. The value of x is then null.
My question is how do I set up my hierarchy so that I can
get the value of x when I switch to a linked list?
Any help appreciated
Edited by: sabatier_sabrika on Oct 28, 2008 9:32 AMsabatier_sabrika wrote:
I have a variable that should only be set once and stays
constant even tho the user may switch between an array
and a linked list. So, say
constant variable x
List myList = new Array();
myList.set(x) = 10;
myList = new LinkedList();I assume that this is pseudo-code, as it definitely doesn't compile.
>
In my current implementation, I am losing the value of x
after I switch to a linked list. The value of x is then null.
My question is how do I set up my hierarchy so that I can
get the value of x when I switch to a linked list?That's a rather curious requirement.
There's no way for the new LinkedList object to know of the content in the Array object in your example.
You can however provide a constructor for your classes that takes a List and initializes its content with that List:
List myList = new Array();
myList.add(x);
myList = new LinkedList(myList);This way the new LinkedList contains the content of the Array. -
Problem with LinkedList and Sets
So I am trying to generate a set using LinkedList. Here is my code: public class MyLLSet implements MySet {
private Node head;
protected int MAX_ELEMENTS;
public MyLLSet(){
head = null;
public MyLLSet(int n){
MAX_ELEMENTS = n;
Node p = head;
int count = 0;
Random randomGenerator = new Random();
while (count < n){
int randomInt = randomGenerator.nextInt(6);
if(this.head == null){
p = new Node(randomInt, null);
System.out.println(p.Element);
p = p.next;
else if(!this.isIn(randomInt)){
p = new Node(randomInt, null);
//System.out.println(p.Element);
p = p.next;
else {
count--;
count++;
public boolean isIn(int v){
Node p = head;
System.out.println(v);
boolean statement = false;
System.out.println(p.Element);
while(p!=null){
if (p.Element == v){
statement = true;
break;
p = p.next;
return statement;
}and my node code: public class Node {
Integer Element;
Node next;
public Node(Integer data){
this( data, null );
public Node(Integer data, Node n){
Element = data;
next = n;
}the problem I am having is adding my randomInt to a node and keeping it there. Then I am trying to send the value to the isIn() method to check if it is already in the set. If not it will add it. When I try to create a set I just get a blank set. Any help would be much appreciated.
Thanks!
ps. there are some print() statements in there just for debugging.Sorry I forgot to add my interface:
public interface MySet{
public boolean isIn(int v);
public void add(int v);
//public void remove(int v);
//public MySet union(MySet s);
//public MySet intersect(MySet s);
//public MySet difference(MySet s);
public int size();
public void printSet();
} -
Search LinkedList and display to JtextArea
The user will type in a first name and hit the "go" button. If the name is in the list it should say the person's name is in the list in the JTextArea, if not it should say the person's name is not in the list in the JTextArea. I have the basic layout, but am lost on how to get what the user typed in the JTextField and the button click and display to textarea to all play together.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class FirstName extends JFrame {
private static final String names[] = { "Joe", "Mark", "David", "Bryan","Amber","Abigail","Skyler","Melanie" };
private javax.swing.JButton jButton1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private java.awt.Label label1;
public FirstName() {
initComponents();
List link = new LinkedList(Arrays.asList(names));
setSize( 400, 200 );
show();
private void initComponents() {
jPanel1 = new JPanel();
label1 = new Label();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jTextArea1 = new javax.swing.JTextArea();
label1.setText("Enter a Name to Search:");
jPanel1.add(label1);
jTextField1.setColumns(20);
jPanel1.add(jTextField1);
jButton1.setText("Go");
jButton1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
MouseClicked(evt);
jPanel1.add(jButton1);
jTextArea1.setColumns(30);
jTextArea1.setRows(5);
jPanel1.add(jTextArea1);
getContentPane().add(jPanel1, BorderLayout.CENTER);
private void MouseClicked(MouseEvent evt) {
public static void main(String args[]) {
FirstName application = new FirstName();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}I'm getting a Syntax error on token "(",";"expected
for actionPerformed, what is wrong?
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class FirstName extends JFrame {
private String names[] =
"Joe",
"Mark",
"David",
"Bryan",
"Amber",
"Abigail",
"Skyler",
"Melanie" };
private JButton jButton1;
private JTextArea jTextArea1;
private JPanel jPanel1;
private JTextField jTextField1;
private Label label1;
public FirstName() {
initComponents();
List link = new LinkedList(Arrays.asList(names));
setSize(400, 200);
show();
private void initComponents() {
jPanel1 = new JPanel();
label1 = new Label();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jTextArea1 = new javax.swing.JTextArea();
label1.setText("Enter a Name to Search:");
jPanel1.add(label1);
jTextField1.setColumns(20);
jPanel1.add(jTextField1);
JButton1 = new JButton1(" OK ");
jbutton1.addActionListener(new ActionListener(this));
public void actionPerformed(ActionEvent e) {
String entered = jTextField1.getText();
// search for "entered" within the list
if (found) {
jTextArea1.setText("found");
} else {
jTextArea1.setText("not found");
jPanel1.add(jButton1);
jTextArea1.setColumns(30);
jTextArea1.setRows(5);
jPanel1.add(jTextArea1);
getContentPane().add(jPanel1, BorderLayout.CENTER);
public static void main(String args[]) {
FirstName application = new FirstName();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} -
Paging using LinkedList and jsps
Hi all,
I have large number of records in my database. I am storing the resultset in LinkedList. Now i want to display that linkedList across different pages say having 100 records per page & every thing should be generic. Please help out if anybody knows.
thanks in advance.Why you do this?
Let's assume that you have 1 million rows, are you going to put all of it in the list? -
Do we have LinkedLists and NODEs(Circular,linear etc ) in Java
Hi ,
Please suggest me some good information to learn about NODEs in Java.....
Thanks ,
Rajesh Reddy[Linear nodes usually make the musical sound of the drum, while circular nodes make the 'thump' sound.|http://209.85.229.132/search?q=cache:pKWk2HZ9-toJ:strikeachord.questacon.edu.au/assets/strike_a_chord_drum_dance.rtf+node+circular+linear&hl=en&ct=clnk&cd=5&gl=uk]
Or maybe you are asking about nodes as elements in a List? -
Why LinkedList uses doubly linked list and not single link list
Hi,
Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
Edited by: user4933866 on Jun 26, 2012 11:22 AM
Edited by: user4933866 on Jun 26, 2012 11:25 AM
Edited by: EJP on 27/06/2012 08:50: corrected title to agree with questionEJP wrote:
Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again. -
Hi,
I was just curious as to how a LinkedList would work in the following case:
[ A ] -------> [ B ] ---------> [ C ]
Say I am currently at position B in the LinkedList and I decide to remove the element at position B, would position C still be the next element in the list or would it now be an element D??
Also, what are the benefits of using a ListIterator rather than just using a for loop and the add(index) or remove (index) methods, similar to how an array works??Hi,
I was just curious as to how a LinkedList would work
in the following case:
[ A ] -------> [ B ] ---------> [ C ]
Say I am currently at position B in the LinkedList
and I decide to remove the element at position B,
would position C still be the next element in the
list or would it now be an element D??Next position will still be C.
>
Also, what are the benefits of using a ListIterator
rather than just using a for loop and the add(index)
or remove (index) methods, similar to how an array
works??Because that is really slow. You can only access e.g. element 100 by starting at the beginning (or the end) and iterate till you get to the correct position.
Kaj -
Help using ListIterator to traverse a tree
Need help traversing a tree.
I have built the tree and now I am trying to traverse it to print it out. The main tree is a LinkedList, and each object on the list has a LinkedList of "children" which may or may not be empty.
My thought was to have a local ListIterator in each LinkedList and use hasNext() and next() to return the objects. So I build the tree, then I try to reset the local iterator for everyone in the tree. But it's not working. If I initialize the ListIterator in the LinkedList class, I get a "ConcurrentModificationException" when I try to access the list. Or if I don't initialize the ListIterator but try to set it later, I get a "NullPointerException" at the same point.
My questions are these:
Should I be able to keep a local ListIterator in the LinkedList?
And if so, am I doing it right?
Should I be able to "reset" the ListIterator after having created it?
And if so, am I doing that right?
Is there a different way I should be traversing my tree?
And, my burning question about this whole ListIterator thing: It appears from the online docs that a ListIterator is an Interface and not an Object. How can the listIterator method return an Interface?
Here's my code:
// the tree class
public class PartTree
private Part rootPart;
private File dataModel;
private PartList theTree;
private Part currentPart;
public PartTree(String dmPath, String rootPartType)
throws FileNotFoundException, IOException
rootPart = new Part();
dataModel = new File(dmPath);
lostKids = new PartList();
theTree = new PartList();
rootPart.setName(rootPartType);
rootPart.setChildList(theTree);
refresh();
public void refresh()
throws FileNotFoundException, IOException
theTree = new PartList();
String line;
Part ptr;
try
BufferedReader in =
new BufferedReader(new FileReader(dataModel));
line = new String(in.readLine());
line = in.readLine();
while(null != line)
ptr = new Part(line);
insertPart(ptr);
line = in.readLine();
catch(FileNotFoundException e)
throw new FileNotFoundException(e.getMessage());
theTree.resetTreeIter();
currentPart = rootPart;
// the linked list class
public class PartList extends LinkedList
private Iterator listIter;
//private Iterator listIter = listIterator(0);
public synchronized void resetTreeIter()
listIter = listIterator(0);
Part ptr;
Iterator it = listIterator(0);
while( it.hasNext() )
ptr = (Part)it.next();
if( ptr.hasKids() )
ptr.getChildList().resetTreeIter();
public synchronized Part nextPart()
if( listIter.hasNext() )
return (Part)listIter.next();
return null;
}I know I am getting to the resetTreeIter method because when I replaced all the code there with a new exception, that got displayed.
Thanks for any help,
ConnieMuch though I hate the Visitor pattern, this does look like a good use of it. If you define an interface public interface PartVisitor
public void visit(Part part);
} and add a method to Part public void acceptPreOrder(PartVisitor visitor)
visitor.visit(this);
if (hasKids())
Iterator it = getChildList().iterator();
while (it.hasNext())
it.next().acceptPreOrder(visitor);
}Then to print them, you merely say topLevelPart.accept(
new PartVisitor()
public void visit(Part part)
System.out.println(part);
});/ -
Array of linkedlist of object - help! plesse!
I am writing an array of linkedlist and the elements of the linkedlist is an object carrying 2 interger. It didn't compile and the message is as follows:
C:\thesis5>javac testLL2.java
testLL2.java:22: cannot resolve symbol
symbol : variable vertexFanObj2
location: class testLL2
vertexFanObj2 = myLL2[ i].get(j);
^
1 error
My program is as follows:
import java.net.*;
import java.io.*;
import java.util.LinkedList;
public class testLL2 {
public static void main(String[] args) throws IOException {
int myLLLength;
Integer intObj;
LinkedList myLL2 [] = new LinkedList[10];
vertexFan vertexFanObj;
for (int i = 0; i < 10; i++) {
myLL2[ i] = new LinkedList();
for (int j=0; j < 5; j++) {
vertexFanObj = new vertexFan();
vertexFanObj.setupVertex(j, -j);
myLL2.add(vertexFanObj);
for (int i = 0; i < 10; i++) {
myLLLength = myLL2[ i].size();
for (int j=0; j<myLLLength; j++) {
vertexFanObj2 = myLL2[ i].get(j);
System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
class vertexFan {
int vertex1, vertex2;
void setupVertex(int vertexA, int vertexB) {
vertex1=vertexA;
vertex2=vertexB;
I 've got lost! Please kindly help you! Many thanks in advance!for (int i = 0; i < 10; i++) {
myLL2[ i] = new LinkedList();
for (int j=0; j < 5; j++) {
vertexFanObj = new vertexFan();
vertexFanObj.setupVertex(j, -j);
myLL2.add(vertexFanObj);
for (int i = 0; i < 10; i++) {
myLLLength = myLL2[ i].size();
for (int j=0; j<myLLLength; j++) {
vertexFanObj2 = myLL2[ i].get(j);
System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
} Its a scope issue.
You define vertexFanObj in a for loop. then try to access it from outside that for loop. (in another for loop)
for (int i = 0; i < 10; i++) {
myLL2[ i] = new LinkedList();
vertexFanObj = new vertexFan(); //I MOVED THIS LINE
for (int j=0; j < 5; j++) {
vertexFanObj.setupVertex(j, -j);
myLL2.add(vertexFanObj);
for (int i = 0; i < 10; i++) {
myLLLength = myLL2[ i].size();
for (int j=0; j<myLLLength; j++) {
vertexFanObj2 = myLL2[ i].get(j);
System.out.println(vertexFanObj.vertex1+" "+vertexFanObj.vertex2);
} should work properly... -
I have a LinkedList and want to go through all the objects-elements in the list with a loop. They say the 'for' loop is not the best way.
It is better to use an Iterator but I don't know how to use it.
Could anyone help me?
Thanks.I have a LinkedList and want to go through all the
objects-elements in the list with a loop. They say
the 'for' loop is not the best way.
It is better to use an Iterator but I don't know how
to use it.
Could anyone help me?
Thanks.You don't know how to use an iterator? -
What would happen if two concurrent threads try and remove ....
Hello,
I have a java test to give back tomorrow and I'm stuck on this question, could you help me please.
Question: What is the difference between java.util.Vectorand java.util.ArrayList?
I read everywhere that: The main difference between Vectors and ArrayLists is that Vectors are synchronized so any method that touches the Vectors content is thread safe, which is not the case for ArrayLists.
This part is ok.
Now the second part of the question is:
What would happen if two concurrent threads try and remove the third object
of such a collection?
I don't know what to answer. I could tell that if the vector or arraylist is smaller than 3 il will return an ArrayOutOfBoundException but what happen if they are longer?
Thank you very much.RaptorKiller wrote:
Hello,
I have a java test to give back tomorrow and I'm stuck on this question, could you help me please.
Question: What is the difference between java.util.Vectorand java.util.ArrayList?
I read everywhere that: The main difference between Vectors and ArrayLists is that Vectors are synchronized so any method that touches the Vector’s content is thread safe ...hm. hmmm...
I wouldn't say anything about Vector or its methods being thread safe.
Thing is, [Vector javadoc|http://java.sun.com/javase/6/docs/api/java/util/Vector.html|javadoc] does not state anything like that.
Rather opposite, javadoc says Vector hates concurrent modification just like any other non-concurrent collection: +"...The Iterators returned by Vector's iterator and listIterator methods are fail-fast: if the Vector is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException... Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification..."+
This part is ok.I don't think this part is OK. I would stick with wording given in javadoc: +"Unlike the new collection implementations, Vector is synchronized"+ // synchronized does not necessarily mean thread safe, and Vector is the case proving that
Maybe you are looking for
-
Long time for Adobe Media Encoder to encode 3 minute video
I created a Premiere Pro project with a dynamic link to Adobe After effects (both CS4 versions). Upon finishing this PremPro project which is a 3 minute song with 3d animation playing in the background, I chose Export Media. Since first try was takin
-
Alternate of Skydrive pro for offline capability in sharepoint 2013.
Hi Everyone, I have been working on offline solution for sharepoint 2013. The volume of data in sharepoint is huge(like 2 TB). Almost every user will have access to more than 25000 documents. Initially I picked Skydrive Pro client(which comes with of
-
PhoneGap Build does not connect!
Hi, i'm trying to use the PhoneGap Build feature of Dreamweaver CS6. But i only get time outs and the message, that there are server problems. if i go to the phonegap website there is no problem logging in with my AdobeID. so obviously NO server prob
-
Hi Just bought new Mac Mini, Snow Leopard. Partitioned HD with Boot Camp. Gave Windows 250Gb. Formatted Partition by Windows CD to NTFS. Installed Windows. After the install is complete Windows reboots, and I get this error: <windows root>\system32\n
-
"policy.8.0.microsoft.VC80.CRT, type="win32-policy",version="8.0.50727.6195"publicKey Token="1fc8b3b9a1e18e3b",processorArchitecture="x86"" I've tried everything I know to try and fix this problem when trying to install the latest itunes. I just bou