ArrayList matrix - java

I have an ArrayList of ArrayList-s.
How can I initialize the field with given number of rows and number of columns?
I tried this:
ArrayList<ArrayList<E>> field;
public Field(int rows, int cols) {
field = new ArrayList<ArrayList<E>>(rows);
for(ArrayList<E> t : field)
t = new ArrayList<E>(cols);
}
but it doesn't work. How can I do it?

Consider this:
public class Field<E> {
ArrayList<ArrayList<E>> field;
public Field(int rows, int cols) {
field = new ArrayList<ArrayList<E>>(rows);
for (int i = 0; i < rows; i++) {
ArrayList<E> row = new ArrayList<E>(cols);
for (int j = 0; j < cols; j++) {
row.add(null);
}
field.add(row);
}
}
public static void main(String[] args) {
Field<String> field = new Field<String>(10, 10);
}
}

You don't need to initialize the size of a List.
The main reason to use a List is that its size can change.
With a List you can just do this:
// declare and initialize List of Lists
List<List<Foo>> listOfFooLists = new ArrayList<List<Foo>>();
// create a List from some method
List<Foo> someFooList = createListOfFoos();
// add the List to the List of Lists
listOfFooLists.add(someFooList);
// get the first Foo from the first list of Foos
Foo f = listOfFooLists.get(0).get(0);

Related

How to I call a method to create arrays from another class?

So I have this code in the main class
public class OneDArrays
{
public static int[] create (int size)
{
int[] a1 = new int[size];
for (int i = 0; i < size; i++)
{
a1[i] = i*2+1;
}
return a1;
}
public int sumSome (int[] b1, int howmany)
{
int sum = 0;
if (howmany <= b1.length)
{
for (int i = 0; i < howmany; i++)
{
sum = sum + b1[i];
}
}
else
{
sum = -1;
}
return sum;
}
public int[] grow (int[] c1, int extra)
{
int[] newArray = new int[c1.length+extra];
for (int i = 0; i < newArray.length; i++)
{
while (i <= c1.length)
{
newArray[i] = c1[i];
i++;
}
newArray[i] = 0;
}
return newArray;
}
public void print (int[] d1)
{
for (int i = 0; i < d1.length; i++)
{
System.out.println (d1[i] + ", ");
}
}
}
And then I have my tester class,
public class OneDArraysTester
{
public static void main (String[] args)
{
int[] test1;
test1.create (5);
}
}
How do retrieve the method from the first class? I get the error that "create" is an undeclared method. If the "create" method were a constructer, I know I could just type create test1 = new create (5) but I don't see a way to turn it in to a constructer, so what's the way of doing that but for a method?
You invoke a static method with the classname. Literally className.methodName. Like,
int[] test1 = OneDArrays.create(5);
You have made a class named OneDArrays so you can call it's methods by creating an instance or object of that class.
like this :
OneDArrays ObjectOfClass = new OneDArrays();
int test1[] = ObjectOfClass.create(5);
similarly you can also call other methods of that class by accessing methods of this newly created object ObjectOfClass.
like :
sumOfArray = ObjectOfClass.sumSome(test1,3);
int biggerTest1[] = ObjectOfClass.grow(test1,10);
If you want to make create method works as a constructor than you can but you cannot return value from a constructor so you cannot return your array from that constructor.
Since you have declared the create method as static, #ElliotFrisch is the best way. But, it is not always a good idea to make methods static. So another way to achieve what you want would be to make the create method non-static.
public int[] create (int size){/*Method Body*/};
And then create an object of the OneDArray class to access the method.
OneDArrays oneDArrays = new OneDArrays();
int[] test1 = oneDArrays.create(5);
or,
int[] test1 = new OneDArrays().create(5);

Adding multiple "randomly generated" objects to ArrayList results in adding the same object multiple times

I have a class Ttp which has a ArrayList<City>loaded from file. In constructor of Ttp I randomly shuffle a list read from file and assign it to the object.
public class Ttp {
private ArrayList<City> cities;
public Ttp() {
cities = Utils.shuffleArray(Loader.getCities());
}
}
This way I get 10 objects with nicely shuffled arrays:
public static void main(String args[]) {
Loader.readFile("easy_0.ttp");
for(int i=0; i<10; i++){
System.out.println(new Ttp());
}
}
But in this scenario, when I try to create ArrayList<Ttp> I get a collection full of the same objects (instances of Ttp with the same arrays of cities)
public static void main(String args[]) {
Loader.readFile("easy_0.ttp");
ArrayList<Ttp> arrayList = new ArrayList<>();
for(int i=0; i<10; i++){
arrayList.add(new Ttp());
}
arrayList.forEach(System.out::println);
}
Shuffle function:
public static <T> ArrayList<T> shuffleArray(ArrayList<T> arrayList) {
if (arrayList != null && arrayList.size() > 0) {
int numberOfRolls = Random.getGenerator().nextInt((arrayList.size() - arrayList.size() / 3) + 1) + arrayList.size() / 3;
int indexA;
int indexB;
T objectA;
for (int i = 0; i < numberOfRolls; i++) {
indexA = Random.getGenerator().nextInt(arrayList.size());
indexB = Random.getGenerator().nextInt(arrayList.size());
objectA = arrayList.get(indexA);
arrayList.set(indexA, arrayList.get(indexB));
arrayList.set(indexB, objectA);
}
}
return arrayList;
}
To pick random indexes in shuffle function I am using java.util.Random:
public class Random {
private static final java.util.Random generator = new java.util.Random();
public static java.util.Random getGenerator() {
return generator;
}
}
If Loader.getCities() returns the same list every time that means shuffleArray() is shuffling the same list over and over and every Ttp.cities has a reference to the same unitary list.
The fix is to make a copy somewhere. It could be in getCities(), it could be in shuffleArray(), or it could be in the Ttp constructor:
cities = Utils.shuffleArray(new ArrayList<>(Loader.getCities()));

How to retrieve element from ArrayList containing long array

How to retrieve element from ArrayList<long[]>?
I wrote like this:
ArrayList<long []> dp=new ArrayList<>();
//m is no of rows in Arraylist
for(int i=0;i<m;i++){
dp.add(new long[n]); //n is length of each long array
//so I created array of m row n column
}
Now how to get each element?
every element in that list is an array... so you need to carefully add those by:
using anonymous arrays new long[] { 1L, 2L, 3L }
or especifying the size using the new keyword new long[5]
public static void main(String[] args) throws Exception {
ArrayList<long[]> dp = new ArrayList<>();
// add 3 arrays
for (int i = 0; i < 3; i++) {
dp.add(new long[] { 1L, 2L, 3L });
}
// add a new array of size 5
dp.add(new long[5]); //all are by defaul 0
// get the info from array
for (long[] ls : dp) {
for (long l : ls) {
System.out.println("long:" + l);
}
System.out.println("next element in the list");
}
}
You get the arrays the same way you get anything from an ArrayList. For example, to get the tenth long[] stored in the ArrayList, you'd use the get method:
long[] tenthArray = dp.get(9);
You could also have an ArrayList of objetcs that contain an array of longs inside. But the problem so far with your code is that you are not putting any values in each long array.
public class NewClass {
private static class MyObject {
private long []v;
public MyObject(int n) {
v = new long[n];
}
#Override
public String toString() {
String x = "";
for (int i = 0; i < v.length; i++) {
x += v[i] + " ";
}
return x;
}
}
public static void main(String[] args) {
ArrayList<MyObject> dp = new ArrayList();
int m = 3;
int n = 5;
for (int i = 0; i < m; i++) {
dp.add(new MyObject(n));
}
for (MyObject ls : dp) {
System.out.println(ls);
}
}
}

Adding Multiple Values in ArrayList at a single index

I have a double ArrayList in java like this.
List<double[]> values = new ArrayList<double[]>(2);
Now what I want to do is to add 5 values in zero index of list and 5 values in index one through looping.
The zeroth index would have values {100,100,100,100,100}
The index 1 would have values {50,35,25,45,65}
and all of these values are stored in a double array in following order
double[] values = {100,50,100,35,100,25,100,45,100,65}
How can i do it?
#Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit:
If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this:
(I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
How about
First adding your desired result as arraylist and
and convert to double array as you want.
Try like this..
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Your Prepared data.
List<double[]> values = new ArrayList<double[]>(2);
double[] element1 = new double[] { 100, 100, 100, 100, 100 };
double[] element2 = new double[] { 50, 35, 25, 45, 65 };
values.add(element1);
values.add(element2);
// Add the result to arraylist.
List<Double> temp = new ArrayList<Double>();
for(int j=0;j<values.size(); j++) {
for (int i = 0; i < values.get(0).length; i++) {
temp.add(values.get(0)[i]);
temp.add(values.get(1)[i]);
}
}
// Convert arraylist to int[].
Double[] result = temp.toArray(new Double[temp.size()]);
double[] finalResult = new double[result.length]; // This hold final result.
for (int i = 0; i < result.length; i++) {
finalResult[i] = result[i].doubleValue();
}
for (int i = 0; i < finalResult.length; i++) {
System.out.println(finalResult[i]);
}
}
}
ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjList.add(arrObjInner1);
You can have as many ArrayList inside the arrObjList. I hope this will help you.
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
You can pass an object which is refering to all the values at a particular index.
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<connect> a=new ArrayList<connect>();
a.add(new connect(100,100,100,100,100));
System.out.println(a.get(0).p1);
System.out.println(a.get(0).p2);
System.out.println(a.get(0).p3);
}
}
class connect
{
int p1,p2,p3,p4,p5;
connect(int a,int b,int c,int d,int e)
{
this.p1=a;
this.p2=b;
this.p3=c;
this.p4=d;
this.p5=e;
}
}
Later to get a particular value at a specific index, you can do this:
a.get(0).p1;
a.get(0).p2;
a.get(0).p3;.............
and so on.

Get a random subset from a result set in java

I have a set of 100 object.
How can i get a subset of 5 objects from this set ?
I'm doing this for now but it only returns me one object
int size = memberSet.size();
Set<Member> randomSet = new HashSet<Member>();
int item = new Random().nextInt(size);
int i = 0;
for(Member mbr : memberSet)
{
if (i == item){
randomSet.add(mbr);
}
i = i + 1;
}
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
Full example:
public static void main(String... args) {
Set<Member> memberSet = new HashSet<Member>();
for (int i = 0; i < 100; i++)
memberSet.add(new Member(i));
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
System.out.println(randomSet);
}
static class Member {
final int value;
public Member(int value) {
this.value = value;
}
#Override
public String toString() {
return "" + value;
}
}
Although #dacwe solution is much better I can't help myself, on joke, to just say put a for(int i=0; i<5; i++) around everything and move out the Set randomSet = new HashSet();
Outside the for loop :

Categories