ArrayList in Java is the most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic re-sizeable array and used in place of the array. Since we can not modify the size of an array after creating it, we prefer to use ArrayList in Java which re-sizes itself automatically once it gets full. ArrayList in Java implements the List interface and allows null. Java ArrayList also maintains the insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates. ArrayList supports both the Iterator and ListIterator for iteration but it’s 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 a 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 favorited on many core Java interviews with questions like the Difference between ArrayList and Vector or LinkedList vs ArrayList.
But while using ListIterator you need to be a 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 favorited on many core Java interviews with questions like the Difference between ArrayList and Vector or LinkedList 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 a chance of storing different types of elements in an ArrayList which is meant for something and ultimately results in ClassCastException during runtime.
With generics you can create Java ArrayList which accepts the only type of object specified during creation time and results in a 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 an object into ArrayList in Java opposite to add() method of Java 1.4 which accepts any object.
With generics you can create Java ArrayList which accepts the only type of object specified during creation time and results in a 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 an object into ArrayList in Java opposite to add() 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 resizes 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 Collections.synchronizedList() 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 CopyOnWriteArrayList which is added from Java 5 and optimized for multiple concurrent reads.
In CopyOnWriteArrayList 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 "CopyOnWrite" ArrayList in Java. You can also see these free Java Programming courses to learn more about essential Collection classes in Java.
10 Examples of ArrayList in Java
Let's see some examples of creating ArrayList in Java and using them, I have tried to provide as many 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.
1. How to create an ArrayList in Java? Example
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 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 the diamond operator, the angle bracket, you only need to specify on the left-hand side. This can save a lot of space if you are defining an ArrayList of nested types.
ArrayList<String> stringList = new ArrayList<String> ; // Generic ArrayList to store only String ArrayList<String> stringList = new ArrayList<>(); // Using Diamond operator from Java 1.7
2. How to add an element to ArrayList in Java? Example
You can add elements to 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 Java ArrayList will only allow String elements.
stringList.add("Item"); //no error because we are storing String
stringList.add(new Integer(2)); //compilation error
stringList.add(new Integer(2)); //compilation error
3. How to find the size of ArrayList in Java? Example
The size of an ArrayList in Java is the 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.
int size = stringList.size();
4. How to find the Index of an element in Java ArrayList
You can use the indexOf() method of ArrayList in Java to find out the index of a particular object. When you use this method, ArrayList internally uses equals() method to find the object, so make sure your element implements equals() and hashCode() or else Object class' default implementation will be used, which compares object based upon memory location.
int index = stringList.indexOf("Item"); //location of Item object in List
5. How to retrieve an element from ArrayList in a loop? Example
Many 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 the Iterator. We will see the use of the Iterator in the next section. If you want to learn more about Iterator, you can also see these Java Collection courses for beginners.
for (int i = 0; i < stringList.size(); i++)
String item = stringList.get(i);
System.out.println("Item " + i + " : " + item);
}
From Java5 onwards you can use foreach loop as well
for(String item: stringList){
System.out.println("retrieved element: " + item);
}
String item = stringList.get(i);
System.out.println("Item " + i + " : " + item);
}
From Java5 onwards you can use foreach loop as well
for(String item: stringList){
System.out.println("retrieved element: " + item);
}
6. How to search in ArrayList? Example
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 the type of object defined in ArrayList creation and returns true if this list contains the specified element.
Alternatively, you can also use Collections.binarySearch() method to see if an object is present inside List or not. ArrayList, Vector, CopyOnWriteArrayList, and Stack implements RandomAccess interface, they can be used for performing a binary search. To see which approach is better, see this article.
Alternatively, you can also use Collections.binarySearch() method to see if an object is present inside List or not. ArrayList, Vector, CopyOnWriteArrayList, and Stack implements RandomAccess interface, they can be used for performing a binary search. To see which approach is better, see this article.
7. How to check if ArrayList is Empty in Java? Example
We can use the 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 the list to check if List is empty or not. If the returned size is zero then ArrayList is empty.
boolean result = stringList.isEmpty(); //isEmpty() will return true if List is empty
if(stringList.size() == 0){
System.out.println("ArrayList is empty");
}
if(stringList.size() == 0){
System.out.println("ArrayList is empty");
}
8. How to remove an element from ArrayList in Java? Example
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 an 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 it's worth noting that remove(Object o) removes the first occurrence of the specified element from this list if it is present. In the 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.
stringList.remove(0);
stringList.remove(item);
For a more detailed discussion on the right way to remove an element from ArrayList, please check this tutorial.
9. How to Copy Data from one ArrayList to another in Java? Example
Many times you need to create a copy of ArrayList for this purpose you can use the addAll(Collection c) method of ArrayList in Java to copy all elements from one ArrayList to another ArrayList in Java. Below code will add all elements of stringList to the newly created copyOfStringList.
ArrayList<String> copyOfStringList = new ArrayList<String>();
copyOfStringList.addAll(stringList);
copyOfStringList.addAll(stringList);
10. How to replace an element at a particular index in ArrayList? Example
You can use the set (int index, E element) method of java ArrayList to replace any element from a particular index. The below code will replace the first element of stringList from "Item" to "Item2".
stringList.set(0,"Item2");
11. How to remove all elements from ArrayList? Example
ArrayList in Java provides a clear() method which removes all of the elements from this list. The below code will remote all elements from our stringList and make the list empty. You can reuse Java ArrayList after clearing it.
stingList.clear();
12. How to convert from ArrayList to Array in Java? Example
Java ArrayList provides you the 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 the 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.
String[] itemArray = new String[stringList.size()];
String[] returnedArray = stringList.toArray(itemArray);
String[] returnedArray = stringList.toArray(itemArray);
If you want to convert ArrayList back to Array then see 3 ways to convert an array into ArrayList in Java
13. How to synchronized ArrayList in Java? Example
Sometimes you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use the Collections utility class for this purpose as shown below.
List list = Collections.synchronizedList(new ArrayList(...));
Though there are other choices also available, for example, if you need a synchronized list then you can also use CopyOnWriteArrayList, which is a concurrent List added on Java 1.5 and performs better than synchronized ArrayList if reading outperforms writing. You can also see this tutorial to understand more about How to synchronize ArrayList in Java?
14. How 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 Arrays.asList(T... a) method for this purpose which returns a fixed-size list backed by the specified array.
ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three"); //this is not read only List you can still update value of existing elements
15. How to loop over ArrayList in Java? Example
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.
Iterator itr = stringList.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
ListIterator listItr = stringList.listIterator();
while(listItr.hasNext()){
System.out.println(itr.next());
}
while(itr.hasNext()){
System.out.println(itr.next());
}
ListIterator listItr = stringList.listIterator();
while(listItr.hasNext()){
System.out.println(itr.next());
}
see How to loop ArrayList in Java for couple of more alternative ways of traversing a List in Java.
16. How to sort ArrayList in Java? Example
You can use Collections.sort(List list) method to sort a Java ArrayList in the natural order defined by the Comparable interface and can use Collections.sort(List list, Comparator c) method to sort your Java ArrayList based on custom Comparator. You can also see this post to sort ArrayList into descending order in Java
17. How to convert ArrayList to HashSet in Java? Example
Most of the 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? HashSet also provides 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 results in fewer objects. See How to convert ArrayList to HashSet in Java for step by step example.
13 Tips to use ArrayList in Java
Now that we have seen more than 10 examples of using ArrayList in Java from creating an instance to populating ArrayList, searching, sorting, and retrieving elements, it's time to revisit some important properties of ArrayList in Java and learn some tips to effectively use ArrayList in Java.
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 a few writes. Since a new copy of ArrayList is created every time a write happens, it can be overkill if used in a write-heavy environment.
The second option is a strictly synchronized collection, much like Vector or Hashtable, but it's not scalable because once the number of the thread increases drastically, contention becomes a huge issue. You can also see these Java Multithreading courses to learn more bout synchronization and concurrency in Java.
2. CopyOnWriteArrayList 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 java.util.concurrent package, along with ConcurrentHashMap and BlockingQueue.
3. When ArrayList gets full it creates another array and uses System.arrayCopy() to copy all elements from one array to another array. This is where insertion takes a lot of time.
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 ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, that's why it’s called fail-fast.
5. ConcurrentModificationException is not guaranteed and it only was thrown at best effort.
6. 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.
7. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity() operation. This may reduce the amount of incremental reallocation due to the 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. The ArrayList class is enhanced in Java 1.5 to support Generics which added extra type-safety on ArrayList. It’s recommended to use the generics version of ArrayList to ensure that your ArrayList contains only a specified type of element and avoid any ClassCastException.
10. Since ArrayList implements List interface it maintains the insertion order of elements and also allows duplicates.
11. If we set ArrayList reference to null in Java, all the elements of ArrayList become eligible for garbage collection in Java, provided there are no more strong references exists for those objects.
12. Always use isEmpty() method to check if ArrayList is empty or not, instead of using size() == 0 check. The former one is much more readable, as shown below
if(!listOfItems.isEmpty(){ System.out.println("Starting order processing); } if(listOfOrders.size() != 0){ System.out.println("Order processing started); }
13. From Java 5 Tiger, ArrayList was made parametrized and you should always use the generic version of this class. This prevents the classical error of insertion fish in the list of fruits, or insertion dice in the list of cards. When you use generics, those errors will be caught by the compiler.
Consequently, it also prevents ClassCastException at runtime because compiler ensures right kind of object is stored and retrieved from Collection. It also removes the need for the manual cast, as the Java compiler automatically adds an implicit cast.
For beginners, understanding generics is a little bit tricky, but it's worth learning as nobody uses a collection without generics nowadays. You can also see these Java Collections and Stream courses to learn more about Collections and Generics in Java.
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 in Java. For a Java programmer, as much important is to know about Collection classes, equally important is developing an 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 an index-based data-structure which means it provides O(1) search performance if you know the index, similarly adding an element into ArrayList is also O(1) performance in best case, but if addition trigger resizing of list then it would be on level of O(n) because that much time will be spent on copying elements of old list into new ArrayList.
Most of the time two factors drives your decision, performance, and functionality. ArrayList is an index-based data-structure which means it provides O(1) search performance if you know the index, similarly adding an element into ArrayList is also O(1) performance in best case, but if addition trigger resizing of list then it would be on level of O(n) 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 in the concurrent environment.
That's all about ArrayList examples in Java. We have seen several examples of using ArrayList in Java as well as see some useful tips to deal with ArrayList. You have also learned when to use ArrayList which is very important for every Java programmer. Now, you are ready to use ArrayList in Java.
Other Java ArrayList tutorials you may like
If you are interested to learn more about the ArrayList class, one of the most useful classes from the Java collection framework, then you might like the following articles as well:
If you are interested to learn more about the ArrayList class, one of the most useful classes from the Java collection framework, then you might like the following articles as well:
- ArrayList and HashMap Performance Improvement in JDK 7 (read more)
- How to convert ArrayList to Set? (read more)
- How to sort an ArrayList in reverse order in Java? (solution)
- How to remove duplicate elements from ArrayList in Java? (solution)
- How to clone an ArrayList in Java? (solution)
- How do you convert a Map to a List in Java? (solution)
- Java - How to initialize an ArrayList with values in Java? (example)
- Difference between an ArrayList and a Vector in Java? (answer)
- How to make an ArrayList unmodifiable in Java? (solution)
- 21 ArrayList interview questions with answers (ArrayList questions)
- How to sort ArrayList by multiple fields in Java? (sort a list)
Thanks for reading this article so far. If you like this Java ArrayList tutorial and my example of different ArrayList methods then please share with your friends and colleagues. If you have any questions, please drop a note.
By mistake you have mentioned that the following statement will allow only strings(You have forgotten to add 'String' type)
ReplyDeleteArrayList stringList = new ArrayList();
Hi, What is difference between Arraylist and Linkedlist in Java . Also there is a new arraylist in java 5 called CopyOnWriteArraylist how exactly it is different from java.util.ArrayList ? When should we not use Arraylist and use Linkedlist instead ?
ReplyDeleteHi There, Can we add multiple arrays in an arraylist, say example i have list of hashmap objects in two different arrays and i want to merge these two hashmap lists in an arraylist.
ReplyDeleteyes you can do this.
ReplyDelete1) create two arraylist object from two array.
2. copy second arraylist data into first arraylist using method addAll().
3) discard second arraylist.
The line:
ReplyDeleteArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three");
needs a "}" at the end to complete the ArrayInitializer
Hi Can you pls post example to show
ReplyDeletehow ArrayList in Java which re-size itself automatically ?
if we create a arraylist a = new arraylist[2];
if u add more than two elements what will happen?
pls post it as example
Hi BHARATH,
ReplyDeleteArrayList resize itself by creating another array and copying element from original array to new array by using System.arrayCopy() method. for exact code you can look ArrayList Class on JDK. its free and source comes when you install JDK on your machine.
What's the difference between Collections.synchronizedList and Vector class?
ReplyDeletenice examples. here is my example using objects not with an primitive data types.
ReplyDeletehttp://www.myrmidons.co.in/2011/11/core-java-list-and-arraylist-example.html
What is advantage of iterating through ArrayList as compared to looping through ArrayList ? i.e. I can get elements from ArrayList by using Iterator or by using get(index) method , which one is faster and which one is better , please elaborate ?
ReplyDeleteAssuming capacity is more elements are not going to be added once ArrayList is populated, consider this - create an array list using "new ArrayList(int initialCapacity)" ? Will it perform better compared to an ArrayList created by "new ArrayList();"
ReplyDelete@johmif thanks for your comment and good to know that you like this Java arraylist example and tutorial. @Advait when we create ArrayList(int initialCapacity) we specify size otherwise it will start with default size which is 10 and re-size it accordingly. resizing of arraylist is time consuming operation because content of one array is copied into another array. so if you know the size in advance you can prevent this resizing of arraylist.
ReplyDeleteI'm not an expert, but I think the code from #1:
ReplyDeleteArrayList stringList = new ArrayList();
Would be more correctly stated as
ArrayList stringList = new ArrayList();
Please advise.
what is difference in two code example, sorry Can you please highlight , both arraylist examples looked same to me.
ReplyDeletefor (int i = 0; i
ReplyDeleteString item = stringList.get(i);
}
Why all the errors and non-working code examples???
Best ArrayList tutorial in Java, easily explained most of the task java programmer should perform with ArrayList. would have been even better if you have included sorting and searching on Arraylist in Java.
ReplyDeletehello.if i want to display two things in one item like contact number and name then how can add in listarray?plz reply me on jagruti.sangani@inextrix.com
ReplyDeleteHow can I get middle element from ArrayList, how to get first and last element form elements, though I have an idea that first element is zero and last element should be size-1, I am worrying about empty ArrayList,may be some API methods already out there. Another thing I am intersted in SubList, i.e. part of ArrayList from one index to another, let me know how can we find sublist from ArrayList in java ?
ReplyDeleteFirst of all the statement "This Java ArrayList will only allow String and will throw compilation error if we try to any other object than String.
ReplyDeleteArrayList stringList = new ArrayList();" is wrong and the QA2 is stupid.. its better to test the code & concept b4 do post in this forum..!!
See the below example:
package workset1;
import java.util.*;
public class TstTst {
public static void main(String args[])
{
ArrayList a1 = new ArrayList();
ArrayList a2 = new ArrayList();
HashMap h = new HashMap();
Set s = new TreeSet();
String s1 = "S1";
String s2 = "S2";
String s3 = "S3";
a1.add(s1);
a1.add(s2);
a1.add(s3);
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
Integer i3 = new Integer("3");
a2.add(i1);
a2.add(i2);
a2.add(i3);
ArrayList fin = new ArrayList();
fin.add(a1);
fin.add(a2);
fin.add("Item");
fin.add(new Integer(2));
Iterator it = fin.iterator();
int i=0;
while(it.hasNext())
{
i++;
if(i<3)
{
Object obj = it.next();
ArrayList ao1 = (ArrayList)obj;
Iterator it1 = ao1.iterator();
while(it1.hasNext())
{
System.out.println("Out put: "+it1.next());
}
} else {
System.out.println("Out put: "+it.next());
}
}
}
}
@Raaki, I see what you are saying. actually it was ArrayList i.e. generic version of ArrayList to store only Strings. some how those angle bracket lost, must be I have use them as literal instead of escape version like <. Anyway Thanks for pointing it out.
ReplyDelete**Correction **
ReplyDeleteArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three");
should be
ArrayList stringList = new ArrayList( Arrays.asList(new String[]{"One", "Two", "Three"}));
The list, returned from 'Arrays.asList', needs casting to an Arraylist. Also a '}' was missing from the inner array.
Very nice article..Appreciate for your efforts.Thanks and Keep Posting More...
ReplyDeleteHello Javin, I am getting following error, java.util.arraylist cannot be cast to java.lang.string while converting ArrayList to String e.g.
ReplyDeleteArrayList listOfStudents = getListOfStudents();
String content = (String) listOfStudents;
Can you please help?
Dear Sir,
ReplyDeleteYour articles about Java, and therefore this blog, are a big help to me.
I am trying to learn the Java programming language and every time i come across something new i check your blog for a tutorial explaining this new subject.
I like to thank you and keep up the good work.
Sincerely,
Marc.
Hello Javin, What is difference between capacity and size of ArrayList in Java? Also what is the default capacity when we create instance of ArrayList as aList = new ArrayList(). It would be nice, if you can also explain, how ArrayList resize itself dynamically by using load factor and capacity, as I still has to get hold of this piece.
ReplyDeleteIf anybody is interested on some ArrayList base interview question, which is very important from Java interview point of view, can see this list, which contains questions contributed by community.
ReplyDeleteCan you please explain how can write custom ArrayList without using Collection?
ReplyDeletehow i can loop an arraylist of objects
ReplyDeletesuperb articles on ArrayList in java very nice.....
ReplyDeletepublic class Feldolgozas {
ReplyDeleteArrayList dolg = new ArrayList();
ArrayList hall = new ArrayList();
ArrayList szak = new ArrayList();
ArrayList tan = new ArrayList();
public void Dolg_beol(String filename) {
Scanner scan = null;
try {
scan = new Scanner(new File(filename));
} catch (FileNotFoundException ex) {
System.out.println("Hiba");
}
while (scan.hasNextLine()) {
char azonosito;
azonosito = scan.next().charAt(0);
int id = 0;
String nev = " ";
if (azonosito == 's') {
id = scan.nextInt();
}
if (azonosito == 'i') {
id = scan.nextInt();
}
if (azonosito == 'd') {
id = scan.nextInt();
nev = scan.nextLine();
}
//int id = scan.nextInt();
//String nev = scan.nextLine();
dolg.add(new Dolgozatok(azonosito, id, nev));
}
}
public void Hall_beol(String filename) {
int a = 0;
Scanner scan = null;
try {
scan = new Scanner(new File(filename));
} catch (FileNotFoundException ex) {
System.out.println("Hiba");
}
while (scan.hasNextLine()) {
String nev1 = scan.nextLine();
String nev2 = scan.nextLine();
String nev3 = scan.nextLine();
++a;
hall.add(new Hallgatok(nev1, nev2, nev3, a));
}
}
public void Szak_beol(String filename) {
Scanner scan = null;
int sor = 0;
try {
scan = new Scanner(new File(filename));
} catch (FileNotFoundException ex) {
System.out.println("Hiba");
}
while (scan.hasNextLine()) {
String nev1 = scan.next();
String nev2 = scan.next();
++sor;
szak.add(new Szakosztaly(nev1, nev2, sor));
}
}
public void Tan_beol(String filename) {
Scanner scan = null;
int a = 0;
try {
scan = new Scanner(new File(filename));
} catch (FileNotFoundException ex) {
System.out.println("Hiba");
}
while (scan.hasNextLine()) {
String nev1 = scan.next();
String nev2 = scan.nextLine();
++a;
tan.add(new Tanarok(nev1, nev2, a));
}
}
public void print() {
for (Tanarok t : tan) {
for (Dolgozatok d : dolg) {
for (Hallgatok h : hall) {
if (h.getId() == d.getId() && d.getAzonosito() == 'i') {
//if (h.getId() == d.getId() && d.getAzonosito() == 's') {
if (d.getNev().equals(" ")) {
System.out.println(" 0");
}else{
System.out.println(t.toString());
System.out.println(d.toString());
System.out.println(h.toString());
}
//}
}
}
}
}
}
}
scanner.nextLine();
ReplyDeleteif (line.length() != 0) {
System.out.println("***Line: " + line);
StringTokenizer stk = new StringTokenizer(line, ", .;:?!");
int id = Integer.parseInt(stk.nextToken());
String marka = stk.nextToken();
String szin = stk.nextToken();
double ar = Double.parseDouble(stk.nextToken());
Auto a = new Auto(ar, id, marka, szin);
this.autok.add(a);
}
}
}
public void Listaz() {
for (Auto a : this.autok) {
System.out.println(a.toString());
}
}
public void ListazAr(double ar) {
for (Auto a : this.autok) {
if (a.getAr() == ar) {
System.out.println(a.toString());
}
}
}
public void ListazMarka(String marka) {
for (Auto a : this.autok) {
if (a.getMarka() == marka) {
System.out.println(a.toString());
}
}
}
public void ListazSzin(String szin) {
for (Auto a : this.autok) {
if (a.getSzin() == szin) {
System.out.println(a.toString());
}
}
}
public void ListazId(int id) {
for (Auto a : this.autok) {
if (a.getId() == id) {
System.out.println(a.toString());
}
}
}
}
public class AutoLerakat {
ReplyDeleteprivate ArrayList autok = new ArrayList();
public AutoLerakat() {
}
public void eladoAuto(int id) {
for (Auto a : this.autok) {
if (a.getId() == id) {
this.autok.remove(a);
break;
}
}
}
public AutoLerakat(String file) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
} catch (FileNotFoundException ex) {
System.out.println("Allomany megnyitasi hiba!!");
System.exit(1);
}
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.length() != 0) {
System.out.println("***Line: " + line);
StringTokenizer stk = new StringTokenizer(line, ", .;:?!");
int id = Integer.parseInt(stk.nextToken());
String marka = stk.nextToken();
String szin = stk.nextToken();
double ar = Double.parseDouble(stk.nextToken());
Auto a = new Auto(ar, id, marka, szin);
this.autok.add(a);
}
}
}
public void Listaz() {
for (Auto a : this.autok) {
System.out.println(a.toString());
}
}
public void ListazAr(double ar) {
for (Auto a : this.autok) {
if (a.getAr() == ar) {
System.out.println(a.toString());
}
}
}
public void ListazMarka(String marka) {
for (Auto a : this.autok) {
if (a.getMarka() == marka) {
System.out.println(a.toString());
}
}
}
public void ListazSzin(String szin) {
for (Auto a : this.autok) {
if (a.getSzin() == szin) {
System.out.println(a.toString());
}
}
}
public void ListazId(int id) {
for (Auto a : this.autok) {
if (a.getId() == id) {
System.out.println(a.toString());
}
}
}
}
@Anonymous, Can you please care to explain your long programs? Also in which language they are, never heard something like ListazId
ReplyDelete