Java ArrayList with 2 columns - java

I need to use an array list as I don't know how many rows I will need but I know I'll need 2 columns. I'm unsure of how to create such an array list, add to both columns and read data from both columns. Both columns will contain integers.
I have seen some suggest:
ArrayList<Arraylist<Integer>> name = new ArrayList<ArrayList<Integer>>();
but I can find an explanation of how to add to both columns.
I've also seen:
ArrayList<Integer[][]> name = new ArrayList<Integer[][]>();
and different variations of where and the number of square brackets.
Thanks.

Java is Object Oriented language, so why not create ArrayList<Column> ?
You can create a class Column which will cover your requirements: it can have setters and getters, and if you need to support other types other than Integer you can generify it. For example:
class Column<T> {
private T value;
public Column(T value) {
this.value = value;
}
public getValue() {
return this.value;
}
}
Then you declare:
List<Column<Integer>> list = new LinkedList<>();
list.add(new Column<Integer>(5));
System.out.println(list.get(0).getValue())

Example how create two dimension structure use lists like you to do:
List<List<Integer>> names = new ArrayList<>();
List<Integer> row = new ArrayList<>();
row.add(1); // first column
row.add(2); // second column
names.add(row); // add row with column
System.out.println(names.get(0).get(0)); // get first column from first row
System.out.println(names.get(0).get(1)); // get second column form first row
But best way is use Custom object like this:
class CustomRow {
private int col1;
private int col2;
// getters and setters
}
List<CustomRow> tables;
CustomRow cr = new CustomRow();
cr.setCol1(1);
cr.setCol2(2);
tables.add(cr);

Something like this:
public MyObject {
Integer integer1;
Integer integer2;
}
List<MyObject> myObjList = new ArrayList<>();
MyObject mo = new MyObject(){
...
myObjList.add(mo);

You could try
a Map and use the key and the value to hold values
a List of tuples
a List of Lists as you suggested
You didn't give enough information as to what you actually want to do, but if you have to use a List as a base, I'd typically go with a List of custom Tuple objects, each holding two values.

You can try creating a simple POJO class called Row and have two variables as column1 and column2. Then add this Row object to your list.

You basically need to create an ArrayList that holds an ArrayList of type Integer. You can then add two of these ArrayLists into the main array list.
List<List<Integer>> myList = new ArrayList<>();
List<Integer> x = new ArrayList<>();
x.add(5);
x.add(6);
List<Integer> y = new ArrayList<>();
y.add(5);
y.add(6);
myList.add(x);
myList.add(y);
Based off this answer:
How do I declare a 2D String arraylist?

Related

Vertically separate arraylist to sublists

I have an ArrayList which contains String arrays.
I need to separate this arraylist to sub ArrayLists like separating columns,
like
Arraylist columns to
ArrayList columnOne, ArrayList columnTwo....
No, I need to separate ArrayList to ArrayList like
ArrayList<String[]> data=
["cold","yes"]
["cold","no"]
["hot","no"]
ArrayList<String>
ArrayList<String> columnOne= ["cold","cold","hot"]
ArrayList<String> columnTwo= ["yes","no","no"]
It looks like easy with using loop but may be there is more simple way on initialize ArrayList?
Here is the code you need if I understood well your requirements.
Please adjust the code to test if columnIndex is a valid column index.
You have also to decide what is necessary to do if not all arrays have the same dimension.
public List<String> getColumnList(List<String[]> strArrayList, int columnIndex) {
List<String> columnList = new ArrayList<String>();
for (int i = 0; i < strArrayList.size(); i++) {
columnList.add(strArrayList.get(i)[columnIndex]);
}
return columnList;
}

Multidimensional Arrays in Java

Alright, so I've been working with PHP for most of my career and find myself needing to use Java. In my case, the biggest issue I have is creating and manipulating arrays in Java.
Example in PHP:
$cars = array(1 => array("stats"=> array("velocity"=>100,
"acceleration"=>0,
"energy"=>30000,
"distance"=>200
)
),
2 => array("stats"=> array("velocity"=>3,
"acceleration"=>6,
"energy"=>30000,
"distance"=>200)
)
);
I'm trying to re-create this type of array in Java but I'm having trouble with initializing it. Is the array considered a String in this case? And must the size of the array be set prior to creating it? e.g: String[][][] car = new String[][][]?
Exactly as aet said in a comment - if you're considering doing this in java - don't. You're doing it wrong.
You should have a class for Car
public class Car {
private int velocity;
private int acceleration;
private int energy;
private int distance;
//getters and setters, a constructor that gets all the property values ...
}
and then store your cars in some collection. An ArrayList is the easiest way:
List<Car> cars = new ArrayList<Car>();
cars.add(new Car(100,0,30000,200));
cars.add(new Car(3,6,30000,200));
Accessing the list of cars would then look like this:
cars.get(0).getVelocity(); //collection indexes start at 0
I think Java doesn't have TRUE multidimensional arrays. An array which is accessed like a[i][j][k] is simply an array, of arrays, of arrays.
You can try the following construct:
String[][] car = new String [][] { { "X0", "Y0"},
{ "X1", "Y1"},
{ "X2", "Y2"},
{ "X3", "Y3"},
{ "X4", "Y4"} };
1) is that "stats" index nesserly? if not, you can:
Map<String, Integer>[] cars = new HashMap<String, Integer>[your length here];
this will index your cars by numbers, skip the "stats" index, and allow you to index the last integer by string:
int velocityOfSecondCar = cars[1].get("velocity"); //note indexing from 0
2) if "stats" index is nesserly, you would have to go one dimension deeper
What you have in PHP there would typically be represented as nested Map instances in Java. For example:
HashMap<Integer,Map<String,Map<String,Integer>>> data = new HashMap<>();
Then you could get values (assuming all levels of the Hash are populated correctly) by saying:
int velocity = data.get(1).get("stats").get("velocity");
Populating nested maps like this can be complicated, and you would typically use a helper method to make sure all the 'parent' levels are populated before you add a data member.
Yes, lenghts must be provided when initializing an array. Hence, your array would look something like this:
int lenght1=x;
int length2=y;
int lenght3=z;
String[][][] car = new String[lenght1][lenght2][lenght3]
I'm no PHP developer myself, but Classes within the array will obey the OOP rules Java implements in terms of abstraction and inheritance. So when you retrieve the elements you can use their corresponding interfaces whatever the class or interface that contains them are.
On the other hand, if you can't know the array lenghts before the initialization you can use class ArrayList, which is almost like a Vector. This class modify its internal length if new elements are added. Along with ArrayList you have a complete set of data structures in the Java specs to store the elements, like Maps, Sets, Lists, etc...
When instantiating an ArrayList you should specify which class or interface will describe the objects you are storing within the data structure, so you'll have to use generics to instantiate the structure. In your case:
ArrayList<String> dim1=new ArrayList<String>();
ArrayList<ArrayList<String>> dim2=new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<ArrayList<String>>> dim3= new ArrayList<ArrayList<ArrayList<String>>>();
As you can see this structure is way sexier than the simple arrays above, but obviusly will require more care to deal with it. Don't forget to instantiate your arraylists before putting them in your 3d matrix, or you'll get an exception later for accesing a null objects.
try this..
Map<Integer, HashMap<String, HashMap<String, Integer>>> map = new HashMap<>();
HashMap<String, Integer> hm = new HashMap<>();
hm.put("Velocity", 1);
hm.put("acceleration", 2);
HashMap<String, HashMap<String, Integer>> state1 = new HashMap<>();
state1.put("state1", hm);
map.put(1, state1);
System.out.println(map);

Store and retrieve List in List

I want to know if there are more efficient way to do this.
I am trying to call List from the List
public class GetL{
public List getList(){
List mainList = new ArrayList();
List subList = new ArrayList();
List subList2 = new ArrayList();
subList.add("one");
subList.add("two");
mainList.add(subList);
subList2.add("three");
subList2.add("four");
mainList.add(subList2);
return mainList;
}
}
and I would call it like this.
GetL getL = new GetL();
List tempList = getL.getList();
tempList.get(0);
tempList.get(1);
Is there a more efficient way to achieve the same result?
One of the biggest reason that I don't like this way is that I have to create so many different "List"
edit:
The biggest problem for me is that I am trying to query data from DB (ie id, age, name)and it can be well over 100 sets. And I cannot dynamically declare many List and store into "mainList"
My original design was using while loop and clear the list.
while( something ){
subList.add(something);
subList.add(something2);
mainList.add(subList);
subList.clear();
}
I didn't know clear() list also clear the stored value in mainList...
You could do something like this:
/**
* Returns a list of lists containing Foo objects.
*/
public List<List<Foo>> getListOfLists() {
ResultSet rs = // get data from database...
List<List<Foo>> mainList = new ArrayList<List<Foo>>();
for (Row r : rs) {
List<Foo> subList = new ArrayList<Foo>();
for (Foo f : r.getFooList()) {
subList.add(f);
}
mainList.add(subList);
}
return mainList;
}
The above code assumes that your database query returns a ResultSet.
It also assumes that each row from the ResultSet has a method that returns a list of Foo objects.
Each sub-list contains objects of type Foo (which you can replace with whatever class you're using).
For a more helpful answer, please try to share some example code that shows what you're trying to do.
Right now we can only guess at what you're after...

Confused about arrayList

I got this line of code when I asked the teacher for some help, but I get a redline below the last part. What could be wrong? The error message: "The type of the expression must be an array type but it resolved to ArrayList" I don't understand that, please help me to understand.
ArrayList<Point>[] touchPoints = new ArrayList<Point>()[2];
I want to have two lists to save Points. I guess I call each list like touchPoints[0]; and touchPoints[1]; !?
EDIT:
I guess I can keep it simple and just use two different List like this!?:
points1 = new ArrayList<Point>();
points2 = new ArrayList<Point>();
You have created an array of ArrayLists. This demo shows how they are used together
import java.util.ArrayList;
public class ArraysAndLists {
public static void main(String[] args) {
ArrayList<String>[] touchPoints = new ArrayList[2];
// Adding values
touchPoints[0] = new ArrayList<String>();
touchPoints[0].add("one string in the first ArrayList");
touchPoints[0].add("another string in the first ArrayList");
touchPoints[1] = new ArrayList<String>();
touchPoints[1].add("one string in the second ArrayList");
touchPoints[1].add("another string in the second ArrayList");
// touchPoints[2].add("This will give out of bounds, the array only holds two lists");
// Reading values
System.out.println(touchPoints[0].get(0)); // returns "one string in the first ArrayList"
System.out.println(touchPoints[1].get(1)); // returns "another string in the second ArrayList"
}
}
check out this Question
The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.
You are mixing two things:
Constructing a plain array
Constructing an ArrayList
Constructing an array
A plain array is very low level. Does not have methods, and its length is fixed after you create it.
MyType[] anArray = new MyType[10];
Constructing an ArrayList
ArrayList is just an implementation of a type of Collection
Collection<MyItemType> aCollection = new ArrayList<MyItemType>();
What to do in your case?
You want a plain array of collections (which implementation is ArrayList). So:
// Create the array, use the interface in case you need to change the implementation later on
Collection<Point>[] touchPoints = (Collection<Point>) new Collection[2];
// Create each collection within that array, using the ArrayList implementation
touchPoints[0] = new ArrayList<Point>();
touchPoints[1] = new ArrayList<Point>();
How to do it better?
Try to think about why you need a plain array:
if it's just 2 elements, and always fixed, simply create two member variables.
if number can vary, just create a Collection of Collections (Collection>)
Edit given your use case:
Just create a class to hold your user input:
class UserInput {
public UserInput() {
user1TouchPoints = new ArrayList<Point>();
user2TouchPoints = new ArrayList<Point>();
}
// Add accessors and all
private Collection<Point> user1TouchPoints;
private Collection<Point> user2TouchPoints;
}
If you plan to have more players, simply use a map
class UserInput {
public UserInput() {
usersTouchPoints = new HashMap<Integer, Collection<Point>>();
}
public Collection<Point> getUserTouchPoints(Integer userId) {
return usersTouchPoints.get(userId);
}
public void addUserTouchPoints(Integer userId, Collection<Point> input) {
Collection<Point> points = usersTouchPoints.get(userId);
if (points==null) {
points = new ArrayList<Point>();
userTouchPoints.put(userId, points);
}
points.addAll(input);
}
// Maps a user ID (or index) to its touch points
// If you are using Android, use SparseArray instead of Map, this is more efficient
private Map<Integer, Collection<Point>> usersTouchPoints;
}

Deleting a Int from my ArrayList

I have a Arraylist: ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
from an Object that includes a String and an double (Name and points).
public class PlayerBean{private String name;private double points;}
However for one of my Spinners I want to show only the name (String) in my Arraylist.
How do I manage to delete(remove) the double(points)?
I tried this without any success any ideas?
I am using the swinger for android. any idea?
ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
List<String> namesOnly = filterNames(playerlist);
private List<String> filterNames(ArrayList<PlayerBean> playerlist12) {
List<String> names = new ArrayList<String>();
for(PlayerBean b : playerlist12)
{
names.add(b.getName());
}
return names;
}
Your list contains PlayerBean objects and you can't temporarily delete member variables from objects. Thus you can't remove points from the list.
You could either use a List<String> instead or provide a spinner model that only displays the name. I assume you're using Swing, don't you?
Rather than removing them, why don't you make a new array List of String type, and assign all the names into this list. So you don't have any points.

Categories