简体   繁体   中英

creating arrays within ArrayList java

I'm trying to create two different types of Arrays within one ArrayList. Set up constructors accordingly (I think), but when it comes to instantiating them I get an error message "arr cannot be resolved". I'm slowly but surely going round the bend. How do I get the ArrayList to accept a simple array with doubles? (It also has to accept other types so it's not just a question of changing the ArrayList itself).Here's the code for the constructors & main ArrayList:

class NumList implements Num
{
    private ArrayList<Num> n1;

    public NumList( NumDouble[] doubleArray ) 
    {           
       n1 = new ArrayList<Num>();
       for( NumDouble d : doubleArray ) 
            n1.add( d );
    }

    public NumList(NumFloat[] floatArray ) 
    {
       n1 = new ArrayList<Num>();
       for( NumFloat d : floatArray ) 
            n1.add( d );

    }
// methods of Num interface
}

And my test class looks like this -

import java.util.ArrayList;

public class Demo extends NumList {
    public Demo(NumDouble[] doubleArray) {  
        //suggested automatically to add super here
        super(doubleArray);

        double[] arr = {(1.1), (2.2), (3.3), (4.4)};
        ArrayList<Num> n1 = new ArrayList<Num>(arr);
    }

    public static void main (String [] args){

        arr.sqrt();

        System.out.println("The numbers sq are "+ arr [0]);
    }
}

The NumList class has just three methods including sort. I have tried wildcards as well as

It's probably something really easy ... any help appreciated.

Your ArrayList holds object of type Num, but you are trying to insert plain ol' doubles into it

double[] arr = {(1.1), (2.2), (3.3), (4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(arr);

double does not inherit from Num and so cannot be placed in an ArrayList<Num> . Also, no ArrayList constructor takes an array as a parameter, you have to convert your array to a collection with Arrays.asList(array) . You would have to do something like this

NumDouble[] arr = {new NumDouble(1.1), new NumDouble(2.2), new NumDouble(3.3), new NumDouble(4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(Arrays.asList(arr));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM