Java ArrayList add methodJava ArrayList add(E element) methodThe ArrayListadd(E element) methodof Java ArrayList classappends a new value to the end of this list. Syntax:Parameter:Here, "element" is an element to be appended to the list. Return:It always return "true". Don't worry about the Boolean return value. It always there as other classes in the collections family need a return value in the signature when adding an element. Example 1Test it NowOutput: [element1, true, last element] Example 2Test it NowOutput: does not compile. This time the compiler knows that only Integer values are allowed in and prevents the attempt to add a String value. Java ArrayList add(int index, E element) methodThe add(int index, E element) method of Java ArrayList class inserts a specific element in a specific index of ArrayList. It shifts the element of indicated index if exist and subsequent elements to the right. Syntax:Parameter:"index": index at which the element will be inserted. "element": is an element to be inserted. Return:Return nothing. Example 3Test it NowOutput: ["black", "red" , "white", "blue"] Example 4Test it NowOutput: [1, "e1", "e2" , 1] Example 5Test it NowOutput: throwsIndexOutOfBoundsException Next TopicJava ArrayList |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India