tech_geek23
tech_geek23

Reputation: 229

what does ArrayList<Number> mean?

Here's my current situation:

import java.util.ArrayList;
import java.util.Scanner;

import com.sun.xml.internal.ws.api.pipe.NextAction;

import static java.lang.System.*;

public class NumberAnalyzer
{
private ArrayList<Number> list;

public NumberAnalyzer()
{

}

public NumberAnalyzer(String numbers)
{
    String nums = numbers;
    Scanner chopper = new Scanner(nums);
    while(chopper.hasNext()){
        int num = chopper.nextInt();
        list.add(num);
    }
    list = 
}

How would I go about converting a string of numbers, say 5 12 9 6 1 4 8 6, and add them to this ArrayList<Number> that I have? Eclipse is stating that

The method add(int, Number) in the type ArrayList is not applicable for the arguments (int).

EDIT here are pastebin links to all the associated .java files:

http://pastebin.com/9KDXLwbL (NumberAnalyzer.java)

http://pastebin.com/BGRpbpyH (Number.java)

http://pastebin.com/EhmZ6kKH (runner class)

http://pastebin.com/BCzeZytg (NumberTester.java this one works well with Number.java, which was part one of the lab)

Upvotes: 0

Views: 2688

Answers (3)

Farhan Syed
Farhan Syed

Reputation: 326

If you want to use Parametrized approach, use Integer as the parameter and while adding cast it to Integer.

private ArrayList<Integer> list = new ArrayList<Integer>();
list.add(Integer.valueOf(num));

If you do not want to use the Parametrized approach, simply add it to the list as an int.

private ArrayList list = new ArrayList();
list.add(Integer.parseInt(num));

Upvotes: 0

Simon
Simon

Reputation: 5422

The problem is that you have another class Number. Change your code this way:

import java.util.ArrayList;
import java.util.Scanner;

public class NumberAnalyzer {

    private ArrayList<Number> list;

    public NumberAnalyzer() {
    }

    public NumberAnalyzer(String numbers) {
        list = new ArrayList<Number>();
        String nums = numbers;
        Scanner chopper = new Scanner(nums);
        while (chopper.hasNext()) {
            list.add(new Number(chopper.nextInt()));
        }
        chopper.close();
    }

}

In this way you are using you class Number, and not the default one.

Upvotes: 1

SLaks
SLaks

Reputation: 887767

Apparently, you have your own Number class in the current package.

Thus, your ArrayList<Number> doesn't contain java.lang.Number, but another type entirely. Therefore, you can't add an int to it; the compiler cannot convert an int into an instance of the custom Number class.

Instead, you need to explicitly create an instance of your Number class, or get rid of it and use java.lang.Number. (which int has an implicit conversion to)

Upvotes: 1

Related Questions