0

I am trying to use the Singleton design pattern in ItemControl, but Android Studio says that I cannot assign a value to final variable 'instance'. How can I compile my code if the variable must be static final?

public final class ItemControl {
    private final Map<Long, Item> itemMap = new HashMap<>();
    private static final ItemControl instance;

    private ItemControl() { }

    public static synchronized ItemControl getInstance() {
        if(instance == null) {
            instance = new ItemControl();
        }
        return instance;
    }

    public void addItem(Item item) {
        itemMap.put(item.getId(), item);
    }

    public List<Item> retrieveItems() {
        if(itemMap.isEmpty()) {
            List<Item> items = carregarItems();
            if(items != null) {
                for(Item item : items) {
                    itemMap.put(item.getId(), item);
                }
            }
        }
        return new ArrayList<>(itemMap.values());
    }

    private List<Item> carregarItems() {
        List<Item> items = new ArrayList<>();

        Item.Builder livroBuilder = new Item.Builder(System.nanoTime(), "Java for Beginners")
                .setAno(2013).setAutor("Glauber Rocha").setQuantidade(3)
                .setDescricao("Livro para programadores iniciantes.");

        Item.Builder revistaBuilder = new Item.Builder(System.nanoTime(), "Geek on the table")
                .setAno(2013).setAutor("Robson Duarte").setQuantidade(2)
                .setDescricao("Revista para geeks.");

        items.add(livroBuilder.build());
        items.add(revistaBuilder.build());

        return items;
    }
}

4 Answers4

0

You declared

private static final ItemControl instance;

Since instance is final you can not assign a value to instance in the method getInstance(). It must be assigned when it is declared, in the constructor, or in a initialization block.

That being said, consider implementing your singleton as a enum. See What is an efficient way to implement a singleton pattern in Java? if you can not get rid of it all together.

Community
  • 1
  • 1
bradimus
  • 2,472
  • 1
  • 16
  • 23
0

You need to initialize instance when you declare it:

private static final ItemControl instance = new ItemControl();
jos76
  • 141
  • 1
  • 2
  • 8
  • but I want to have control of this instance... I want to have only one instance of an ItemControl object... and it must be accessible to all parts of my app – Raul Figueira Nov 15 '16 at 18:29
  • Then you can make the instance variable `public static final` and you can access the instance by calling `ItemControl.instance`. Since it's static, it's defined at the class level not the object level so there will only ever be one instance. – jos76 Nov 15 '16 at 18:59
  • You can also have a getter for the instance like Uday describes – jos76 Nov 15 '16 at 19:02
0

This has nothing to do with Android Studio. See, you have the variable instance which has been declared final. And its being assigned in getInstance(). So since its final you cannot assign it anywhere but there itself.

So do this:
private static final ItemControl instance = new ItemControl();

And in getInstance() return that variable

public static ItemControl getInstance() {
        return instance;
    }
Udayaditya Barua
  • 1,151
  • 12
  • 26
  • Ok. I did it. It is working now. How can I do that using enum? I read the topic below, but I didn't understand it. http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java – Raul Figueira Nov 15 '16 at 19:15
0

I fixed it. But I did in the pre-java1.5 way. I didn't understand how to do the same using 'enum'. How can I do the same singleton pattern using enum? I read this topic, but I didn't understand.

public final class ItemControl {
    private final Map<Long, Item> itemMap = new HashMap<>();
    private static final ItemControl instance = new ItemControl();

    private ItemControl() {
        if(instance != null) {
            throw new IllegalStateException("ItemControl já foi instanciado.");
        }
    }

    public static synchronized ItemControl getInstance() {
        return instance;
    }

    public void addItem(Item item) {
        itemMap.put(item.getId(), item);
    }

    public List<Item> retrieveItems() {
        if(itemMap.isEmpty()) {
            List<Item> items = carregarItems();
            if(items != null) {
                for(Item item : items) {
                    itemMap.put(item.getId(), item);
                }
            }
        }
        return new ArrayList<>(itemMap.values());
    }

    private List<Item> carregarItems() {
        List<Item> items = new ArrayList<>();

        Item.Builder livroBuilder = new Item.Builder(System.nanoTime(), "Java for Beginners")
                .setAno(2013).setAutor("Glauber Rocha").setQuantidade(3)
                .setDescricao("Livro para programadores iniciantes.");

        Item.Builder revistaBuilder = new Item.Builder(System.nanoTime(), "Geek on the table")
                .setAno(2013).setAutor("Robson Duarte").setQuantidade(2)
                .setDescricao("Revista para geeks.");

        items.add(livroBuilder.build());
        items.add(revistaBuilder.build());

        return items;
    }
}
Community
  • 1
  • 1