-5

Its a very simple code but cant figure out why i cant use the LinkedList bp;

package Itens;

import java.util.LinkedList;

public class Mochila {
    LinkedList bp = new LinkedList();

    /* Syntax error */
    bp.add();
}

The class Mochila is in a different package(Itens) than main.

2 Answers2

1

You should specify what you are trying to add to the list.

For example :

bp.add("abc");

And it's better not to use the raw LinkedList type. For example, if the list should contain Strings, use :

LinkedList<String> bp = new LinkedList<>();
bp.add ("abc");
Eran
  • 387,369
  • 54
  • 702
  • 768
  • @ViniciusIlidio Do you have some driver class with a main method to test the functionality of said LinkedList because Eran's approach works fine. Please post all `relevant` code you are using for this exercise. – Tdorno Mar 22 '15 at 15:08
0

You can't call bp.add(); in class level. Instructions should be invoked in code blocks like methods, constructors or initialization blocks (where for instance you will be able to handle potential exceptions, if method would be declared to throw them).

Also you need to add something like add(whatever) (there is no no-arbument method add in LinkedList).

Other thing is that you should specify type of elements your list should contain by using generics. More info at What is a raw type and why shouldn't we use it?

Last thing is that if you are not going to use any method which exists only in LinkedList, you should make your code more flexible by using as reference more general (or even abstract) classes or interfaces. More info at What does it mean to "program to an interface"?

So try with

public class Mochila {
    List<String> bp = new LinkedList<>();

    {// this initialization block will be added at start of each constructor
     // of your Mochila class
        bp.add("something");
    }
}
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269