What method can I use in adding or removing an element from my array.
Is there a method for this?
Plus, one that resizes the array automatically in cases when an element is deleted to prevent the default "0" from occupying that space.
You don't have those methods for arrays but you can use ArrayList instead. Code example:
List<String> list = new ArrayList<>();
list.add("str 1");
list.add("str 2");
list.add(0,"str 3"); // Add 3 on position 0
list.remove(1); // remove item on position 1
list.remove("str 2"); // remove first occurrence of str 2
But you can't use primitive type directly as in arrays, if you want ArrayList of int then you will use Integer class which acts as wrapper for primitive type -
List<Integer> list = new ArrayList<>();
So you can't perform all the actions that you mentioned above using arrays.
You might look into using ArrayList class in java. It has in built remove libraries as well.
Check this link out - https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int)
Related
I am new to Groovy and, despite reading many articles and questions about this, I am still not clear of what is going on.
From what I understood so far, when you create a new array in Groovy, the underlying type is a Java ArrayList. This means that it should be resizable, you should be able to initialize it as empty and then dynamically add elements through the add method, like so:
MyType[] list = []
list.add(new MyType(...))
This compiles, however it fails at runtime: No signature of method: [LMyType;.add() is applicable for argument types: (MyType) values: [MyType#383bfa16]
What is the proper way or the proper type to do this?
The Groovy way to do this is
def list = []
list << new MyType(...)
which creates a list and uses the overloaded leftShift operator to append an item
See the Groovy docs on Lists for lots of examples.
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.
So using def list = [] you can then append new items with add() method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
This question already has an answer here:
How to manage Continuous Changing values in an array of strings [closed]
(1 answer)
Closed 9 years ago.
I have an array of strings but the values in array is changing continuously.
Is there any other way of managing the array except removing items and changing index locations?
public String[] deviceId=null;
deviceId=new String[deviceCount];
in my case deviceCount is changes as new device comes.
so i continuously need to change array size and add or remove items
Use ArrayList in place of String[] ..
And you can also easily cast ArrayList to String[] for your final output as
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
You could use a List. It changes size depending on how many objects you put in it.
List<String> list = new ArrayList<String>;
public static void main(String[] args) {
list.add("string 1"); //Add strings to the list
list.add("string 2");
System.out.println(list.get(0)); //Get the values from the list
System.out.println(list.get(1));
}
Instead of using Arrays, you could use ArrayLists. You can add as much as you want to them without having to re-size the array and once you no longer need an item it can be removed. Here is a link to an overview of ArrayLists and some examples using them: http://www.tutorialspoint.com/java/java_arraylist_class.htm
Hope this helps.
If you know the max count of devices. Then you can define an array with max size.
String[] deviceId = new String[MAX_DEVICE_COUNT];
Or else simply go with a List.
List<String> deviceId=new ArrayList<String>();
Don't worry about performance, so much with a array.
- In Java arrays are initialized at the time of its creation whether its declared at class level or at local level.
- Once the size is defined of an array in Java it can't be changed.
- Its better to use Collection like List.
- It has the flexibility to add and delete the items in it, and one can also at items at desired location in the List.
- List is an Interface in Java, you can use its concrete sub classes like ArrayList, LinkedList..etc.
Not sure whether i got the question correctly but you can use ArrayList or LinkedList if the size is going to change dynamically.
I start learning the Java generic collection using Deitel Harvey book - but I am facing a difficulty understanding the three line of codes below - Do all of them perform the same operation on by intializing and adding the relevant values of array ( colors ) to the LinkList variable (list1). How does the second method and third method works - I am having a bit difficulty understanding how Arrays can viewed as a list.. As I know arrays are not dynamic data structure, they have fixed sized length, adding/ removing elements on array can not be done on running time comparing to Lists in general.
String[] colors = { "black", "white", "blue", "cyan" };
List< String > list1 = new LinkedList< String >();
// method 1 of initalizing and adding elments to the list
for (String color : colors)
list1.add(color);
// method 2 of initializing and adding elements to the list
List< String > list1 = new LinkedList< String > (Arrays.asList(colors));
// method 3 of initializing and adding elements to the list
List< String > list1 = Arrays.asList(colors);
Please help me understand my queries above, don't judge me as I am still new to this.
Thank you, Sinan
Actually knowledge of generics is not necessary for answering this question.
As you correctly identifier arrays are static in the sense that you can't add elements to them or remove them.
Lists, however, usually allow those operations.
The List returned by Arrays.asList() does have the add/remove methods (otherwise it would not be a valid List). However actually calling those methods will throw an UnsupportedOperationException exactly because you can't actually add elements to an array (for which this List is simply a view/wrapper).
Operations that don't structurally modify the list (i.e. that don't change the number of elements in the list) are entirely possible: set(int, E) works just fine on the List returned by Arrays.asList().
Arrays.asList returns a fixed-size list backed by the specified array.
It is actually a bridge between Array and Collection framework. But returned list write through to the array.
Only your first method does anything to the LinkedList you have initially assigned into list1. The other two assign a new, unrelated list to it. The third option assigns something that isn't a LinkedList, but a special implementation of the List interface backed by your String array. In the third case you won't be able to add/remove elements from the list, but you can iterate over it and update existing slots. Basically, it does what a plain array does, just through the List interface.
Arrays.asList creates a List from an Array. Arrays in general can't be viewed as lists in Java. They can only be wrapped in a list.
So method 2 is used to have a specific list implementation LinkedList in this case.
to Method 2, just check the Api here:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList(java.util.Collection)
For sure, Lists implement the Collections Interface so this Constructor will work here.
to Method 3, just check out the Api here: http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
Every time you are interested in implementation you can look into certain method. For example, by press Ctrl+left mouse button onto method or class.
// method 2 of initializing and adding elements to the list
List<String> list1 = new LinkedList<String> (Arrays.asList(colors));
This code leads to:
List<String> list1 = new LinkedList<String> (new ArrayList<String>(colors));
In constructor of ArrayList:
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
the actual array is copied to encapsulated private array field(link is copied).
Then in constructor of LinkedList:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
Every element of passed collection is added to the LinkedList.
if you see the link below
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList%28java.util.Collection%29
you will see the constructor of linked list class which is accepting a collection object as parameter.
Any in your post, the 2nd and 3 rd lines are passing an object of collection class(i.e Arrays.asList is finally giving a List which is a sub class of collection).
So both 2nd and 3rd lines fairly valid implementations.
More over you can observe one more good coding practice in all the 3 lines.
That is
writing code to interceptors than to classes
. (referring
LinkedList
instance with
List
interface)
Always try to refer your classes with interceptors which is a good practice
I have an array
String[] path={abc,bcd};
I pass this array in a method:
addElement(path);
In method
void addElement(String[] path)
{
// here i got value suppose "qsd" and i want to add it after "bcd" ie 2 index of array
path[path.lenght]="qsd";
}
But this is giving me an error.
I dont want to use an ArrayList.
The biggest problem is that arrays in Java are not trivially resizable. What you wind up doing instead is actually creating a new array, and adding each of the elements to that. This will be slower than the ArrayList code, and uglier as well.
This also means that any code which points to the old array will no longer work. If you only have one instance, you could have addElement return the new array like so
String[] addElement(String old[]){
String arr[] = new String[old.length+1];
//copy all the elements in old...
arr[old.length] = "whatever";
return arr;
}
Then use
path = addElement(path);
You should use ArrayList
Otherwise you have to resize the array by allocating new memory of the size of the original array +1, copy the elements from the old one to the new one, and add in the new element.
You can't change the size of emulated array in GWT (even if javascript arrays support this stuff). You'll have always to create a new instance of array. Most common way to solve this problem is to use one of the collection classes (like java.util.ArrayList) . Example:
ArrayList<String> path = new ArrayList<String>(Arrays.asList("abc","bbc"));
path.add("qsd");
Can you give any reasonable example for a ArrayList<ArrayList<E>>, such as declaring, initializing, adding elements and iterating them. Is this one of the way to get 2-dimensional Array behavior in Java?
Yes, an ArrayList<ArrayList<E>> is similar to a two-dimensional array of E (E[][]). It has all the common differences between using a List and using arrays in Java (List is a higher-level API, supports resizing, adding elements at arbitrary positions, ...).
You don't treat it any different from a normal List, except that the elements it contains are actually other List objects:
Initialize it:
ArrayList<ArrayList<E>> listOfLists = new ArrayList<ArrayList<E>>();
Iterate over it:
for (ArrayList<E> innerList : listOfLists) {
doSomethingWithInnerList(innerList);
}
Add to it:
ArrayList<E> newInnerList = new ArrayList<E>();
// add stuff to newInnerList
listOfLists.add(newInnerList);
The only thing I want to add to Joachim Sauer's answer is that yes, an ArrayList<ArrayList<E>> can be similar to a two-dimensional array of E (E[][]) with one additional twist (in addition to all the usual differences between one-dimensional arrays and lists):
Using a list of lists, you can make the equivalent of a "jagged" array. Not all of the inner lists need to have the same size(), whereas in a two-dimensional array, all of the "rows" of E[][] by definition have identical lengths. It's "rectangular". A list of lists doesn't have to be rectangular; it can be jagged.
ArrayList is used to hold array of objects. On the other it can have duplicate values. when you need a fast insertion/deletion you can use it. it holds the values in the same order as it is entered into it. For example
List<String> ls= new ArrayList<String>();
ls.add("foo");
ls.add("bar");
for(String val:ls){
System.out.println("Value :" + val);
}