Using an arraylist combined with an array - java

So I want to use an arraylist combined with an array, essentially a 2d array list but with the first level as an array list and the second level as an array.
I know that arraylists or arrays can be used as 2d alone, but my first set of data I don't know the size, whereas the second set I know the size to be 30
To give an example the array list should contain names something like
{"bob", "dave", "pete", "alan"}
and then for each name I want to attach an array of size 30, if I was using just arrays I imagine it'd be something like
String[][] array = new String[?][30]();
and then I'd add the names using something like
array[0] = "bob";
and then add data using
array[0][0] = 1;
but I want the first one to be an arraylist
Sorry if this isn't clear, feel free to ask for more explanation

There are several possible approaches.
1) If you don't care about the order of the items, you could use a Map<String, String[]>, with the names ("bob") as keys, and the arrays of length 30 as the values.
2) You could have two separate ArrayLists - one for the names, and one for the arrays. The downside of this is that you have to be careful to update them together.
List<String> names;
List<String[]> values;
3) You could create an Entry class that contains a name and a values array, then store these Entry objects in an ArrayList.
class Entry {
String name;
String[] values;
// etc
}
...
List<Entry> entries = new ArrayList<Entry>(); //etc

Related

How to append data into a String list in Java

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.

How to sort multiple arrays of different types (int and String)

So I read from a text file, line by line, some information and I basicly save it in memory to arrays of different types (string and int). In total I have 2 arrays of String and 6 of int.
I want to sort 1 of the arrays (String) alphabetically and based on that sort the other arrays of string and ints in positions that were saved.
Text file example: B,United States,3,1,0,2,2,7
C,United Kingdom,3,1,2,0,2,1
A,Denmark,3,3,2,0,2,1
Those arrays that I mention are saved whenever I read one line in the text file. So, I have a string,string,int,int,int,int,int in the position 0 for starters and so on until the last line is read.
Ps: After I read the text file I'm not supposed to have again the text file and only work with the information saved in memory. (not working with objects)
Create a single Object which represents a combination of the data types that you have for a single 'entry', and make it implement Comparable for that type.
public class MyEntry implements Comparable<MyEntry> {
private String theStringToSortOn;
private String theOtherString;
private int theFirstInt;
private int theSecondInt;
// ...
public int compareTo(final MyEntry entry) {
int comparison = String.compare(this.theStringToSortOn, entry.theStringToSortOn);
if (comparison != 0) {
return comparison;
}
// Do some other rudimentary sorting based on the other fields of the class.
}
}
Then all you need to do is add these to a List and sort it.
If you're intent on sticking with the array based implementation however, then you'll need to give some form of way to identify which indices have changed in the array that you sort (and what they changed from and to), and then mirror those changes to the other arrays.
Without writing code for you, here's a naive implementation of how to achieve this with just arrays:
Take a copy before you sort the array so you can track where indices moved to.
Create another array of ints, of the same length as this array.
Sort the array.
Iterate over the original, and for each element iterate over the sorted one to find the new index.
Store this new index in your array of ints (in the position which denotes the unmodified index).
Use this 'sorting/index array' to change the indices of all of the other arrays that you need to sort according to the first one.

How can add an element to an array?

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.

Java add variable to string array

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());

INTERSECT result of 2 ArrayList containing Integer values

I've two ArrayList both containing Integer values. My objective is to get identical/common/duplicate values comparing these 2 list. In other words (in SQL parlance), I need the INTERSECT result of two lists, that is, values that appear in both list.
Example:
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(500);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(300);
list2.add(600);
One kind of implementation/solution I could think along is looping one of the list something like:
ArrayList<Integer> intersectList = new ArrayList<Integer>();
for (Integer intValue : list1)
{
if(list2.contains(intValue))
intersectList.add(intValue);
}
In this case, intersectList would contain only 1 Integer item being added, that is 300, which appears in both list.
My question is, are there any better/fastest/efficient way of implementing this logic? Any options available in Apache Commons library?. Any other ideas/suggestions/comments are appreciated.
NOTE: For illustration purpose, I've just shown here 5 items and 2 items being added into the list. In my real-time implementation, there will be more than 1000 elements in each list. Therefore, performance is also a key factor to be considered.
If you're okay with overwriting result for list1:
list1.retainAll(list2);
otherwise clone/copy list1 first.
Not sure on performance though.
list1.retainAll(list2)//for intersection
Use ListUtils from org.apache.commons.collections if you do not want to modify existing list.
ListUtils.intersection(list1, list2)

Categories