I have a small code that includes citynames which will be displayed.
Now a want a user can add names with a scanner, I know the code for the scanner but not how to add the variable.
Code I have:
String[] cityNames = { "Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" };
System.out.println(Arrays.toString(cityNames));
No you cannot do it with a Array since the size is fixed , once it declared.
You are probably looking for Collections. Prefer to Use List interface with ArrayList implementation.
The reason is that the ArrayList is
Resizable-array implementation of the List interface.
List<String> cityNames = new ArrayList<>();
Now you have methods like add, remove, ... and many more useful methods on your cityNames List
You can use a List<String>, get the input value and add it:
List<String> cities = new ArrayList<>();
cities.add(userInput);
List is better to use than array as its length is modifiable.
Arrays have a fixed length. If the amount of Strings in your collection is variable, you´ll have to use a List.
You can add new element to array if index of new element less than the size of array.
arr[i]="some value" // to do this i < arr.length
If array is completely filled with elements when you assign new value to index previous value will override. You can't add more elements than the size of declared since array has fixed size.
Array is fixed size so you can't add the value to it if the size is already filled. For dynamic array use List instead of array.
Do like this
List<String> list = new ArrayList<String>(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" ));
list.add("new value1");
list.add("new value2");
It's better to use there set, which excludes duplicate entries automatically:
Set<String> cities = new HashSet<String>();
cities.addAll(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren"));
then to add new city just call:
sities.add(newCity);
Scanner input = new Scanner(System.in);
List<String> cityNames = new ArrayList<String>();
//Add the city names to cityNames list...
cityNames.add(input.next());
Related
I have an array:
String[] a = {"abc","def","ghi"}
Now I want to store this array into my string arraylist
ArrayList<String> arr = new ArrayList<>();
so that it becomes like this:
[["abc","def","ghi"]]
I have tried this code but it doesn't work:
arr.add(Arrays.asList(a));
Please help me
Since Arrays.asList(a) returns List, to add it to your list you need to use addAll()
arr.addAll(Arrays.asList(a));
Instead of
arr.add(Arrays.asList(a));
But the result will be ["abc","def","ghi"]
If you want to achieve this [["abc","def","ghi"]] then define your ArrayList as
List<List<String>> arr = new ArrayList<>();
using arralist addAll() method we can do but,
Using arrayList is depricated approach , use Streams instead of it:
System.out.println(Collections.singletonList(Stream.of(new String[] {"abc","def","ghi"}).collect(Collectors.toList())));
will result in:
[[abc, def, ghi]]
I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.
Need some help to understand how I can put all the elements from an ArrayList to a single Array. Not sure if its possible to do it in a single Array.
Declaration
List componentNameList = new ArrayList();
String[] componentNameItem = soapApiCall.getComponentNames();
componentNameList.add(Arrays.toString(componentNameItem));
Here is the element of the ArrayList:
[[Index, Pattern, Smart, Intell][Index, Tree, Pet, Intel][Index, Pattern, Bear, Intell, Dog][Sky, Intern, Blond]]
Expected output for the Array
<Index><Pattern><Smart><Intell><Index><Tree><Pet><Intel><Index><Pattern><Bear><Intell><Dog><Sky><Intern><Blond>
Thanks in advance.
First, I'd suggest you not use raw types, nor do I suggest to add the string representation of an array to a raw type list.
Thus, change this:
List componentNameList = new ArrayList();
to this:
List<List<String>> componentNameList = new ArrayList<>();
then change this:
componentNameList.add(Arrays.toString(componentNameItem));
to this:
componentNameList.add(new ArrayList<>(Arrays.asList(componentNameItem)));
Then you can accomplish the task at hand with streams like below:
String[] resultSet = componentNameList.stream()
.flatMap(List::stream) // flatten
.toArray(String[]::new); // collect to array
then print:
System.out.println(Arrays.toString(resultSet));
I don't have idea how to search this:
Random generator = new Random();
Map<Integer, ArrayList> mapOfprevOp = new HashMap<>();
ArrayList<Integer> listPrev = new ArrayList<>();
listPrev = mapOfprevOp.get(operacja);
System.out.println(listPrev); // it will show []
int rnd = generator.nextInt(op_cnt) + 1;
listPrev.add(rnd);
System.out.println(mapOfprevOp.get(operacja)); // it will show value of listPrev
Why second System.out print me on the screen value of listPrev?
It shouldn't still print [] ?
listPrev = mapOfprevOp.get(operacja);
This line works different than i could expect?
This would suggest that at your first System.out.println invocation the list is empty.
If you look here https://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString%28%29. We can see that the toString method for a list returns the elements between square brackets. Thus [] is an empty list.
At the second call you have added an element which is why you see it. You need to bare in mind that in Java we pass objects by reference meaning that your listPrev references the SAME LIST as the one contained in the map.
If you want to just get the value, then I would suggest you change
listPrev = mapOfprevOp.get(operacja);
to be
listPrev.addAll(mapOfprevOp.get(operacja));
This will add all of the elements from mapOfprevOp.get(operacja) to listPrev without subsequent operations affecting the map which seems to be what you want.
Also, Map<Integer, ArrayList> mapOfprevOp = new HashMap<>(); Generally it is better to use interface types in delcarations like you have with Map. So I would consider switching ArrayList to be List.
The object that you use its self can still be an ArrayList, like this:
Map mapOfprevOp = new HashMap<>();
List listPrev = new ArrayList<>();
This means that if you wanted to change it to be a LinkedList, you would only change it in one place rather than 3. Note that with the exception of Arrays.asList lists all lists can be resized.
I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.