0

I am doing a school project in java and I am trying, in a method, to refer to the class.

import java.util.ArrayList;

public class NumberIndex extends ArrayList<Integer> {
  private int s;
  public NumberIndex (){
    super();
    s = 10; // would be better if it was class.size() 
            //but I don't know how to refer to the class
  }
  public NumberIndex (int x){
    super(x);
    s = x;
  }
  public void addWord(int num) {
    for(i = 0; i < s; i++)
      //trying to make it so that for each Integer in ArrayList,
      // if there exists an Integer that has the value num, nothing would
      //happen. Else creates new Integer and adds it to the List

So in order for me to finish this code, all I need is a way to reference the class object NumberIndex itself.

5
  • 2
    It appears you should be using a Set<Integer> which is a collection without duplicates and you would be better off not having an s value and it can only bring your grief. Commented Jan 17, 2016 at 22:11
  • 1
    Google the static keyword. You can reference the actual class object with NumberIndex.class. Commented Jan 17, 2016 at 22:14
  • @PeterLawrey School requires me to do it this way Commented Jan 17, 2016 at 22:30
  • @engineer Sorry. It is a mistake on my part. Commented Jan 17, 2016 at 22:30
  • @kuhnroyal I need to create an an object so I can't use static. However, I will look into NumberIndex.class Thanks for that tidbit Commented Jan 17, 2016 at 22:30

1 Answer 1

2

Since add word is a member function use this. that refers to the current NumberIndex object.

EDIT:

public class NumberIndex extends ArrayList<Integer> {

    public NumberIndex() {
        super(10);//setting the size of your NumberIndex object -> list size
    }

    public NumberIndex(int x) {
        super(x);//setting the size of your NumberIndex object -> list size
    }

    public void addWord(int num) {
        if(!this.contains(num)){//if the current NumberIndex object (list) does not contain num
            this.add(num);//to the current NumberIndex object (list) add num
        }
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Would it be this.NumberIndex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.