Search code examples
javaarraylistincompatibletypeerror

Incompatible types error in ArrayList but both are String


I'm fairly new to Java so don't attack me lol but I've created two classes and an ArrayList in one of them. I can't compile and get this error: "incompatible types: java.lang.String cannot be converted to int" but nothing is being converted here? First class:

import java.util.ArrayList;
public class TestScores {
 private ArrayList < Class > scores;
 public int studentScores;
 public TestScores() {
  scores = new ArrayList < Class > ();
 }
 public void add(String name, int score) {
  scores.add(new Class(name, score));
 }
}

Second Class:

public class Class {
 public int score;
 public String name;
 public Class(int aScore, String aName) {
  score = aScore;
  name = aName;
 }
}

Solution

  • Firstly, don't call a class Class. There's a built-in class called Class: https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

    While it's allowed, it's just unclear. Get into the habit of giving things descriptive names.

    Your error is caused by the arguments being backwards. You construct a new Class like:

    new Class(name, score)

    But your constructor expects score first, then name:

    public Class(int aScore, String aName)

    Arguments in Java, unlike they sometimes are in Python, are matched by position not name. So you tried to bind the local String name to the int parameter aScore, hence the compile error.