-4

I want to add methods to return the list or particular element and I want it to work with any generic class. Why isnt Java allowing this?

class ArrayListBuilder<E>{
    private ArrayList<E> a_list=new ArrayList<>();
}
Samrat Das
  • 57
  • 6
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the source code you have as a [mcve], which can be compiled and tested by others. Your code works fine, it can be compiled and used. What is the problem you have? – Progman May 30 '20 at 08:16
  • See if this answers your question. https://stackoverflow.com/questions/4492950/java-generics-arraylist-initialization – Harmandeep Singh Kalsi May 30 '20 at 08:21
  • @Progman that *is* an MVC. You can't go any more minimal, verifiable and complete than that. The actual problem with that question is that OP doesn't say what happens with that code other than a generic "java isn't allowing this". – Federico klez Culloca May 30 '20 at 08:22
  • My code is throwing an error E cannot be resolved to a type – Samrat Das May 30 '20 at 08:22
  • 1
    @SamratDas you're missing an import for `java.util.ArrayList`. That's the only way you could get the error you say you're getting with your code. Also, you should read *all* of the error messages, not just the last one. – Federico klez Culloca May 30 '20 at 08:25
  • Yeah thanks that was the issue – Samrat Das May 31 '20 at 06:24

1 Answers1

2

I tried to compile your code and got these errors

ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list=new ArrayList<>();
            ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
ArrayListBuilder.java:2: error: cannot find symbol
    private ArrayList<E> a_list=new ArrayList<>();
                                    ^
  symbol:   class ArrayList
  location: class ArrayListBuilder<E>
  where E is a type-variable:
    E extends Object declared in class ArrayListBuilder
2 errors

As you can see there actually are two errors, the first one meaning that you need to import java.util.ArrayList. Once you do that, your code compiles fine. So put in the first line of your code

import java.util.ArrayList;

TL;DR: the solution to your problem is reading all of the error messages. Not just the last one.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95