Вы находитесь на странице: 1из 3

Addthis

Javarevisited
Blog about my exper ience in Java pr ogr amming, SQL, UNIX, Inter view questions, FIX Pr otocol, Tibco RV , JavaScr ipt, jQuer y, Equity tr ading technologies, SQL, XML, UNIX, Linux, Er r or , Exception and best pr actices.

T H UR S DA Y , M A Y 26, 2011

Recommended Reading 5 books to master object oriented and Java design patterns 5 Good books to learn Spring Framework 5 Must read jQuery books for Programmers 9 Must read Java Programming Books for Developers Which programming book to buy, if given $100 to spend Subscribe To This Blog Free Posts Comments Follow Us Follow @javinpaul

10 example of using ArrayList in Java >>> Java ArrayList Tutorial


ArrayList in Java is most frequently used collection class after HashMap in Java . Java ArrayList represents an automatic re-sizable array and used in place of array. Since we can not modify size of an array after creating it, we prefer to use ArrayList in Java which re-size itself automatically once it gets full. ArrayList in Java implements List interface and allow null. Java ArrayList also maintains insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates. ArrayList supports both Iterator and ListIterator for iteration but its recommended to use ListIterator as it allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the Iterator's current position in the list. But while using ListIterator you need to be little careful because ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous () and the element that would be returned by a call to next (). In this Java ArrayList tutorial we will see how to create Java ArrayList and perform various operations on Java ArrayList. This collection class is also favorites on many core Java interviews with questions like Difference between ArrayList and Vector or LinkedList vs ArrayList.

ArrayList has been modified in Java5 (Tiger) to support Generics which makes Java ArrayList even more powerful because of enhanced type-safety. Before Java5 since there was no generics no type checking at compile time which means there is chance of storing different type of element in an ArrayList which is meant for something and ultimately results in ClassCastException during runtime. with generics you can create Java ArrayList which accepts only type of object specified during creation time and results in compilation error if someone tries to insert any other object into ArrayList in Java; for example if you create an ArrayList of String object you can not store Integer on it because add() method of ArrayList will check Type before adding object into ArrayList in Java opposite to add() method of Java4 which accepts any object.

Java ArrayList with Generics in JDK 1.5


Its also important to remember that ArrayList is not synchronized and should not be shared between multiple threads. If multiple threads access a Java ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (As per Java doc a structural modification is any operation that adds or deletes one or more elements, or explicitly re-sizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the C o l l e c t i o n s . s y n c h r o n i z e d L i s t method. Its recommended to synchronize the list at the creation time to avoid any accidental non synchronized access to the list. Another better option is to use C opyOnWriteArrayList which is added from Java 5 and optimized for multiple concurrent read. In C opyOnWriteArrayList all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array and that's why it is called as "C opyOnWrite"

Recent Posts

Database Website to Run and Practice SQL Query Online for FREE - SQLFiddle What is PriorityQueue data structure in Java with Example - Tutorial How clone method works in Java JSTL forTokens Tag Example - Split String in JSP How Maven find dependency JARs while building Java Project

Example of ArrayList in Java


Let's see some example of creating ArrayList in java and using them, I have tried to provide as much example as possible to illustrate different operations possible on Java ArrayList. Please let me know if you need any other Java ArrayList examples and I will add them here. 1) Creating an ArrayList You can use ArrayList in Java with or without Generics both are permitted by generics version is recommended because of enhanced type-safety. In this example we will create an ArrayList of String in Java. This Java ArrayList will only allow String and will throw compilation error if we try to any other object than String.

10 Equals and HashCode Interview Questions in Java


Followers Join this site
w ith Google Friend Connect

Members (1447) More

Already a member? Sign in

A r r a y L i s t < S t r i n g >s t r i n g L i s t=n e wA r r a y L i s t < S t r i n g > ( ) ;/ / G e n e r i cA r r a y L i s tt oS t o r eo n l y S t r i n go b j e c t s


2) Putting an Item into ArrayList Second line will result in compilation error because this Java ArrayList will only allow String elements .

Subscribe by email: Subscribe By Javin Paul


Searc h

s t r i n g L i s t . a d d ( " I t e m " ) ;/ / n oe r r o rb e c a u s ew ea r es t o r i n gS t r i n g s t r i n g L i s t . a d d ( n e wI n t e g e r ( 2 ) ) ;/ / c o m p i l a t i o ne r r o r
3) Checking size of ArrayList Size of an ArrayList in Java is total number of elements currently stored in ArrayList.

Blog Archive 2013 ( 123 ) 2012 ( 217 )

i n ts i z e=s t r i n g L i s t . s i z e ( ) ;

2011 ( 145 ) December ( 28 )


4) Checking Index of an Item in Java Arraylist You can use indexOf() method of ArrayList in Java to find out index of a particular object.

November ( 14 ) October ( 14 ) September ( 22 ) August ( 11 ) July ( 7 )

i n ti n d e x=s t r i n g L i s t . i n d e x O f ( " I t e m " ) ;/ / l o c a t i o no fI t e mo b j e c ti nL i s t

5) Retrieving Item from arrayList in a loop Many a times we need to traverse on Java ArrayList and perform some operations on each retrieved item. Here are two ways of doing it without using Iterator. We will see use of Iterator in next section.

June ( 9 ) May ( 6 ) 10 example of using ArrayList in Java >>> Java... Why wait notify and notifyAll called from synchron... Top 30 UNIX command Interview Questions asked in I... 10 points about Java Heap Space or Java Heap Memor... Tibco Tutorials for beginners Top 10 tips on logging in Java - Tutorial April ( 10 )

f o r( i n ti=0 ;i<s t r i n g L i s t . s i z e ( ) ;i + + ) S t r i n gi t e m=s t r i n g L i s t . g e t ( i ) ; S y s t e m . o u t . p r i n t l n ( " I t e m"+i+":"+i t e m ) ; } F r o mJ a v a5o n w a r d sy o uc a nu s ef o r e a c hl o o pa sw e l l f o r ( S t r i n gi t e m :s t r i n g L i s t ) { S y s t e m . o u t . p r i n t l n ( " r e t r i e v e de l e m e n t :"+i t e m ) ; }


6) Checking ArrayList for an Item Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element. 7) Checking if ArrayList is Empty We can use isEmpty() method of Java ArrayList to check whether ArrayList is empty . isEmpty() method returns true if this ArrayList contains no elements. You can also use size() method of List to check if List is empty

March ( 4 ) February ( 10 ) January ( 10 ) 2010 ( 33 )

References
b o o l e a nr e s u l t=s t r i n g L i s t . i s E m p t y ( ) ;/ / i s E m p t y ( )w i l lr e t u r nt r u ei fL i s ti se m p t y i f ( s t r i n g L i s t . s i z e ( )= =0 ) { S y s t e m . o u t . p r i n t l n ( " A r r a y L i s ti se m p t y " ) ; }
8) Removing an Item from ArrayList There are two ways to remove any elements from ArrayList in Java . You can either remove an element based on its index or by providing object itself. Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicate its worth noting that remove (Object o) removes the first occurrence of the specified element from this list, if it is present. In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.

Java API documentation JDK 6 Spring framework doc Struts ANT Maven JDK 7 API MySQL Linux Eclipse jQuery Copyright by Javin Paul 2012. Powered by Blogger.

s t r i n g L i s t . r e m o v e ( 0 ) ; s t r i n g L i s t . r e m o v e ( i t e m ) ;

9) Copying data from one ArrayList to another ArrayList in Java Many a times you need to create a copy of ArrayList for this purpose you can use addAll(C ollection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java. Below code will add all elements of stringList to newly created copyOfStringList.

A r r a y L i s t < S t r i n g >c o p y O f S t r i n g L i s t=n e wA r r a y L i s t < S t r i n g > ( ) ; c o p y O f S t r i n g L i s t . a d d A l l ( s t r i n g L i s t ) ;

10) Replacing an element at a particular index You can use set (int index, E element) method of java ArrayList to replace any element from a particular index. Below code will replace first element of stringList from "Item" to "Item2".

s t r i n g L i s t . s e t ( 0 , " I t e m 2 " ) ;
11) Clearing all data from ArrayList ArrayList in Java provides clear () method which removes all of the elements from this list. Below code will remote all elements from our stringList and make the list empty. You can reuse Java ArrayList after clearing it.

s t i n g L i s t . c l e a r ( ) ;
12) Converting from ArrayList to Array in Java Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of

the same runtime type is allocated for this purpose.

S t r i n g [ ]i t e m A r r a y=n e wS t r i n g [ s t r i n g L i s t . s i z e ( ) ] ; S t r i n g [ ]r e t u r n e d A r r a y=s t r i n g L i s t . t o A r r a y ( i t e m A r r a y ) ;

If you want to convert ArrayList back to Array than see 3 ways to convert array into arraylist in Java
13) Creating Synchronized ArrayList Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use C ollections utility class for this purpose as shown below.

L i s tl i s t=C o l l e c t i o n s . s y n c h r o n i z e d L i s t ( n e wA r r a y L i s t ( . . . ) ) ;
14) Creating ArrayList from Array in Java ArrayList in Java is amazing you can create even an ArrayList full of your element from an already existing array. You need to use Arrays.asList(T... a) method for this purpose which returns a fixed-size list backed by the specified array.

A r r a y L i s ts t r i n g L i s t=A r r a y s . a s L i s t ( n e wS t r i n g [ ] { " O n e " ," T w o " ," T h r e e " ) ;/ / t h i si sn o tr e a d o n l yL i s ty o uc a ns t i l lu p d a t ev a l u eo fe x i s t i n ge l e m e n t s


15) Traversing in ArrayList in Java You can use either Iterator or ListIterator for traversing on Java ArrayList. ListIterator will allow you to traverse in both directions while both Iterator and ListIterator will allow you to remove elements from ArrayList in Java while traversing.

I t e r a t o ri t r=s t r i n g L i s t . i t e r a t o r ( ) ; w h i l e ( i t r . h a s N e x t ( ) ) { S y s t e m . o u t . p r i n t l n ( i t r . n e x t ( ) ) ; } L i s t I t e r a t o rl i s t I t r=s t r i n g L i s t . l i s t I t e r a t o r ( ) ; w h i l e ( l i s t I t r . h a s N e x t ( ) ) { S y s t e m . o u t . p r i n t l n ( i t r . n e x t ( ) ) ; }

see How to loop ArrayList in Java for more alternative ways of traversing a List
16) Sorting elements of ArrayList in Java You can use C ollections.sort(List list) method to sort a Java ArrayList in natural order defined by C omparable interface and can use C ollections.sort(List list, C omparator c) method to sort your Java ArrayList based upon provided C omparator. You can also see this post to sort ArrayList into descending order in Java 17) ArrayList to HashSet conversion Most of C ollection class provides a constructor which accepts a C ollection object as argument. Which can be used to copy all elements of one C ollection into another. HashSet also provide such constructors which can be used to copy all object from ArrayList to HashSet. But be careful since HashSet doesn't allow duplicates some of the objects will not be included which result in less number of objects. See How to convert ArrayList to HashSet in Java for step by step example.

Tips on ArrayList in Java


1) ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use ArrayList then you need to either use new C opyonWriteArrayList or use C ollections.synchronizedList() to create a synchronized List. 2) CopyonWriteArrayList is recommended for concurrent multi-threading environment as it is optimized for multiple concurrent read and creates copy for write operation. 3) When ArrayList gets full it creates another array and uses System.arrayC opy() to copy all elements from one array to another array. 4) Iterator and ListIterator of java ArrayList are fail-fast it means if ArrayList 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 C oncurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, that's why its called fail-fast. 5) C oncurrentModificationException is not guaranteed and it only thrown at best effort. 6) If you are creating Synchronized List its recommended to create while creating instance of underlying ArrayList to prevent accidental non synchronized access to the list. 7) An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureC apacity operation. This may reduce the amount of incremental reallocation due to incremental filling of ArrayList. 8) The size, isEmpty, get, set, Iterator, and ListIterator operations run in constant time because ArrayList is based on Array but adding or removing an element is costly as compared to LinkedList. 9) ArrayList class is enhanced in Java5 to support Generics which added extra type-safety on ArrayList. Its recommended to use generics version of ArrayList to ensure that your ArrayList contains only specified type of element and avoid any C lassC astException. 10) Since ArrayList implements List interface it maintains insertion order of element and allow duplicates. 11)If we set ArrayList reference null in Java all the elements inside ArrayList becomes eligible to garbage collection in java , provided there are no more reference exists for those objects.

Вам также может понравиться