[Solved] Returning a different type than the parameter


There is a lot that can be improved in your code, let me add some comments

    public void add(String candidate){
    //if candidate is actually null you are calling null.equals
    //which means this will always result in a NullPointerException
    //you can remove this if if you want
    if (candidate.equals(null)){
        throw new RuntimeException();
    }

    ...

    //think about what you are doing here, 
    //you are setting this.candidates to a new empty array 
    //(is big contenders.length, but still empty) 
    this.candidates = new String [contenders.length];

Second part:

    public String get(int index){
    //you are missing an '=' in index >= candidates.length
    if (index < 0 || index > candidates.length) {
        throw new RuntimeException("Your argument was not within bounds.");
    }
    //this for loop is wrong, you are changing 'i' but never use it.. 
    //just return candidates[index] like you said before. 
    //It was probably null because of the error above
    for (int i = index; i < candidate.length(); i++){
        candidate = candidates[index];
    }
    return candidate;

A note on the RuntimeException(RE): if you catch a NullPointerException (NPE) and throw a RE you are actually losing information (since NPE is a more specific error rather than RE). If you want to catch/throw put at least a significant message like “candidate cannot be null”

Let’s now analyze the constructor:

public CandidateList(){
    candidates = new String[0];
}

public CandidateList(String[] candidates){

    // you are doing the same error as above here:
    // when you do this you create an EMPTY list of size candidates.lenght
    // correct code is this.candidates = candidates
    this.candidates = new String[candidates.length];

    // this is not necessary, constructors don't need to return anything, 
    //here you are just creating a new instance that will not be used anywhere
    CandidateList candidateList = new CandidateList();

Constructors create objects, they don’t return data. I suggest you to take a look at this question Does a Java constructor return the Object reference? and in general read a bit more about constructors

10

solved Returning a different type than the parameter