dimanche 25 mai 2014

Java - créer une nouvelle classe ayant des fonctions similaires comme un ArrayList, erreurs dans l'ajout de valeurs ? -Débordement de pile


import java.util.ArrayList;

public class Sequence {

private ArrayList<Integer> values;

public void Sequence(){
values = new ArrayList<Integer>();
}

public void addValue(int ad){
this.values = values;
values.add(ad);
}

public String toString(){
return values.toString();
}

public static void main(String[] args) {
Sequence a = new Sequence();
a.addValue(1);
a.addValue(2);
System.out.println(a.toString());
}
}

I'm relatively new to programming, I bet this is a very silly question, but I cannot figure out why I'm getting an error for this. The idea of the assignment is to create a class called a Sequence that is similar to an ArrayList, and give it new methods, but I can't get the method to simply add new values to the ArrayList. I'd appreciate any help!




The reason for why you're getting a NullPointerException is because you haven't actually defined a constructor, instead you have defined a method called Sequence. A constructor does not have a return type, like void and instead would just be defined, in this case, as:


public Sequence() { 
values = new ArrayList<Integer>();
}


import java.util.ArrayList;

public class Sequence {

private ArrayList<Integer> values;

public void Sequence(){
values = new ArrayList<Integer>();
}

public void addValue(int ad){
this.values = values;
values.add(ad);
}

public String toString(){
return values.toString();
}

public static void main(String[] args) {
Sequence a = new Sequence();
a.addValue(1);
a.addValue(2);
System.out.println(a.toString());
}
}

I'm relatively new to programming, I bet this is a very silly question, but I cannot figure out why I'm getting an error for this. The idea of the assignment is to create a class called a Sequence that is similar to an ArrayList, and give it new methods, but I can't get the method to simply add new values to the ArrayList. I'd appreciate any help!



The reason for why you're getting a NullPointerException is because you haven't actually defined a constructor, instead you have defined a method called Sequence. A constructor does not have a return type, like void and instead would just be defined, in this case, as:


public Sequence() { 
values = new ArrayList<Integer>();
}

0 commentaires:

Enregistrer un commentaire