0

Hey I'm new to Java and have been having difficulties with arrays. I'm trying to use either arrays or arrayLists to store a list of values from my test class. But I'm having on how to add set1 and set2 into my arrayList.

I have a test class with

Data set1 = new Data(new double[]{1, 2, 3, 4, 5});
    System.out.println("Set1: " + set1);

Data set2 = new Data(new double[]{-5, -4, -3, 1});
        System.out.println("Set2: " + set2);

Then my data class

    import java.util.ArrayList;

    public class Data {

    public Data(double[] sets) {
        ArrayList<Double> sets = new ArrayList<Double>();
    }

}
JavaNewbie42
  • 41
  • 1
  • 2
  • 5
  • 1
    you can´t add `set1` and `set2` as they are of the type `Data` and your `ArrayList` requires a `Double` due to generics. You most likely want a constructor `Data(double[])` where you pass the `double` array. in there you could add the values to the `List`. – SomeJavaGuy Dec 13 '16 at 07:08
  • Possible duplicate of [Create ArrayList from array](http://stackoverflow.com/questions/157944/create-arraylist-from-array) – kiner_shah Dec 13 '16 at 07:26

4 Answers4

0

Maybe this would work for you:

public Data(double[] array) {
    sets = new ArrayList<Double>(Arrays.asList(array));
}

public String toString() {
    return sets.toString();
}
Jeremy Gurr
  • 1,613
  • 8
  • 11
0

Firstly create data class as:

class Data
{
   ArrayList<Double> obj;

   Data(Double var[])
   {
      obj=new  ArrayList<Double>();

      for(int i=0;i<var.length;i++)
      {
           obj.add(var[i]);
      }
   }
}

Now create objects of this data class as:

Double val1[]={1.0,2.0,3.0,4.0};
Data set1=new Data(val1);

Double val2[]={1.0,25.0,36.0,44.0};
Data set2=new Data(val2);

Now add these objects of data class into arraylist as:

ArrayList<Data> sets=new ArrayList<Data>();
sets.add(set1);
sets.add(set2);
Manish Sakpal
  • 299
  • 1
  • 9
0

Your problem is in your Data class:

import java.util.ArrayList;

public class Data {

    public Data(double[] sets) {
        ArrayList<Double> sets = new ArrayList<Double>();
    }

}

The sets variable disappears after the constructor returns, so there is no use declaring it there. You should move the declaration to the class level and assign a correct value to it in the constructor:

ArrayList<Double> sets;
public Data(double[] sets) {
    this.sets = new ArrayList<Double>();
    for (double d : sets) {
        this.sets.add(d);
    }
}

Since you want to print the Data, you need to override the toString method:

@Override
public String toString() {
    return sets.toString();
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Here is the code using Java 8 streams,

class Data {

    List<Double> d;

    public Data(Stream sets) {
         this.d = (List<Double>) sets.collect(Collectors.toList());
    }
}

Data setss = new Data(Stream.of("1.1","2","3.4","4","5"));
System.out.println("d list = "+setss.d);
KayV
  • 12,987
  • 11
  • 98
  • 148