일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- reactor core
- reactor
- 서버운영
- Spring Framework
- ipTIME
- 웹 스터디
- 웹앱
- reactive
- 공유기 서버
- Spring Batch
- 웹 커리큘럼
- spring reactive
- Today
- Total
Hello World
10 Examples of using ArrayList in Java 본문
ArrayList in Java is the most frequently used collection class after HashMap. Java ArrayList represents an automatic re-sizeable array and used in place of array. Since we can not modify the 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. ArrayList also maintains the 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 it’s recommended to use 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 when 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 and the element that would be returned by a call to . 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 favourites on many core Java interviews with questions like Difference between ArrayList and Vector orLinkedList vs ArrayList.
ArrayList has been modified in Java 5 (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 in contrast with
method of Java 1.4 which accepts any object.Java ArrayList with Generics in JDK 1.5
It’s 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 method. It’s 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 which is added from Java 5 and optimized for multiple concurrent read. In
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 “ “.
Example of ArrayList in Java
Let’s see some examples of creating ArrayList in Java and using them. I have tried to provide as much examples 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.
Java ArrayList Example 1: How to create 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. This ArrayList will only allow String and will throw a compilation error if we try to any other object than String. If you notice you need to specify the type on both right and left the side of the expression, from Java 1.7 if you use diamond operator, the angle bracket, you only need to specify at left hand side. This can save lot of space if you are defining an ArrayList of nested types.
Java ArrayList Example 2: How to add element into ArrayList
You can add elements into ArrayList by calling add() method. Since we are using Generics and this is an ArrayList of String, the second line will result in a compilation error because this ArrayList will only allow String elements.
Java ArrayList Example 3: How to find size of ArrayList
The size of an ArrayList in Java is a total number of elements currently stored in ArrayList. You can easily find a number of elements in ArrayList by calling size() method on it. Remember this could be different with the length of the array which is backing ArrayList. Actually backing array always has a larger length than the size of ArrayList so that it can store more elements.
Java ArrayList Example 4: Checking Index of an Item in Java ArrayList
You can use
and or else Object class’ default implementation will be used, which compares object based upon memory location.
How to retrieve an element from ArrayList in loop
Many a times we need to traverse on ArrayList and perform some operations on each retrieved item. Here are two ways of doing it without using Iterator. We will see the use of Iterator in next section.
How to search in ArrayList for an element?
Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use this article.
method of Java. method takes the type of object defined in ArrayList creation and returns true if this list contains the specified element. Alternatively, you can also use method to see if an object is present inside List or not. , , and interface, they can be used for performing a binary search. To see which approach is better, seeHow to check if ArrayList is Empty in Java
We can use
method of ArrayList to check whether it is empty. method returns true if this ArrayList contains no elements. You can also use method of List to check if List is empty or not. If returned size is zero then ArrayList is empty.How to remove an element 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
(int index) and method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicate it’s worth noting that removes the first occurrence of the specified element from this list if it is present. In below code the first call will remove the first element from ArrayList while the second call will remove the first occurrence of item from ArrayList in Java.For a more detailed discussion on the right way to remove an element from ArrayList, please check thistutorial.
Copying data from one ArrayList to another ArrayList
Many a times you need to create a copy of ArrayList for this purpose you can use
method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList. Below code will add all elements of to newly created .
How to replace an element at a particular index in ArrayList?
You can use the
( , ) method of Java ArrayList to replace any element from a particular index. Below code will replace the first element of from “ ” to “ “.How to remove all elements from ArrayList?
ArrayList in Java provides a
method which removes all of the elements from this list. Below code will remote all elements from our and make the list empty. You can reuse Java ArrayList after clearing it.How to converting from ArrayList to Array in Java
ArrayList provides you the facility to get the array back from your ArrayList. You can use
method returns an array containing all of the elements in this list in proper sequence (from first to the last element). “ ” 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.If you want to convert ArrayList back to Array than see 3 ways to convert array into ArrayList in Java
How to synchronized ArrayList in Java?
Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.
Though there are other choices also available, for example if you need a synchronized list then you can also use How to synchronize ArrayList in Java?
, which is a concurrent List added on Java 1.5 and performs better than synchronized ArayList if reading outperforms writing. You can also see this tutorial to understand more aboutHow to create 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
method for this purpose which returns a fixed-size list backed by the specified array.How to loop over ArrayList in Java?
You can use either Iterator or ListIterator for traversing on 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.
see How to loop ArrayList in Java for couple of more alternative ways of traversing a List in Java.
How to sort ArrayList in Java?
You can use
method to sort a Java ArrayList in the natural order defined by the interface and can use method to sort your Java ArrayList based upon custom Comparator. You can also see this post to sort ArrayList into descending order in Java
How to convert ArrayList to HashSet in Java
Most of Collection class provides a constructor which accepts a Collection object as an argument. Which can be used to copy all elements of one Collection into another? How to convert ArrayList to HashSet in Java for step by step example.
also provides such constructors which can be used to copy all object from ArrayList to . But be careful since doesn’t allow duplicates some of the objects will not be included which result in less number of objects. SeeTips about ArrayList in Java
- ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use like data-structure in multi-threaded environment, then you need to either use new or use to create a synchronized List. Former is part of concurrent collection package and much more scalable than the second one, but only useful when there are many readers and only few writes. Since a new copy of is created every time a write happens, it can be overkill if used in a write-heavy environment. Second option is a strictly synchronized collection, much like or , but it’s not scalable because once number of thread increases drastically, contention becomes a huge issue.
- is recommended for the concurrent multi-threading environment as it is optimized for multiple concurrent reads and creates copy for the write operation. This was added in Tiger, aka JDK 1.5. It’s part of package, along with and .
- When ArrayList gets full it creates another array and uses to copy all elements from one array to another array. This is where insertion takes a lot of time.
- 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 . Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, that’s why it’s called fail-fast.
- is not guaranteed and it only thrown at best effort.
- If you are creating Synchronized List it’s recommended to create while creating an instance of underlying ArrayList to prevent accidental non-synchronized access to the list.
- An application can increase the capacity of an ArrayList instance before adding a large number of elements using the operation. This may reduce the amount of incremental reallocation due to the incremental filling of ArrayList.
- The , , , , , and operations run in constant timebecause ArrayList is based on Array but adding or removing an element is costly as compared to .
- The ArrayList class is enhanced in Java 1.5 to support Generics which added extra type-safety on ArrayList. It’s recommended to use generics version of ArrayList to ensure that your ArrayList contains only specified the type of element and avoid any .
- Since ArrayList implements List interface it maintains insertion order of elements and also allow duplicates.
- If we set ArrayList reference to
become eligible to garbage collection in Java,
provided there are no more strong reference exists for those objects. in Java, all the elements inside - Always use
- From Java 5 Tiger, was made parametrized and you should always use generic version of this class. This prevents classical error of insertion fish in list of fruits, or insertion dice in list of cards. When use use generics, those error will be caught by compiler. Consequently, it also prevents at runtime because compiler ensures right kind of object is stored and retrieved from Collection. It also removes need of manual cast, as Java compiler automatically adds implicit cast. For beginners, understanding generics is little bit tricky, but it’s worth learning as no body use collection without generics now days.
When to use ArrayList in Java
Now, you know what is ArrayList, different methods of this class and how it works. It’s time now to learn when to use ArrayList. For a Java programmer, as much important is to know about Collection classes, equally important is develop ability to decide which collection to use in a particular scenario. Most of the time two factors drives your decision, performance and functionality.
ArrayList is a index based data-structure which means it provides
search performance if you know the index, similarly adding an element into ArrayList is also performance in best case, but if addition trigger resizing of list then it would be on level of because that much time will be spent on copying elements of old list into new ArrayList. Coming back to functionality, if you are fine with duplicate elements then only use this collection class. It is not thread-safe so don’t use it on concurrent environment.Reference: | 10 Examples of using ArrayList in Java – Tutorial from our JCG partner Javin Paul at theJavarevisited blog. |
출처: http://www.javacodegeeks.com/2016/01/10-examples-using-arraylist-java-tutorial.html
'Java > Core' 카테고리의 다른 글
[펌]Spring의 Singleton과 Java static기반 Singleton패턴의 차이 (0) | 2016.01.14 |
---|---|
ElasticSearch Tutorial for Beginners (0) | 2016.01.12 |
Sending a mail in Java (and Android) with Apache Commons Net SMTP : STARTTLS, SSL (0) | 2016.01.12 |
Unirest for Java (0) | 2016.01.12 |
자바 Primitive Type과 Boxed Primitives 둘 중 무엇을 사용할까? (0) | 2016.01.11 |