1

I want to make a generic container class that can contain one object of some other class. I thought this might be a reasonable approach:

class Container <T> {
    private T thing;

    public void Store(T obj) {
        thing = obj;
    }

    public T ReturnIt() {
        return thing;
    }
}

When I try this together with let's say a Book class, I get the following error message: "Note: GenericContainer.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details."

Could it be that the public T ReturnIt() { return thing; } is the cause of the error, and is this the wrong way to go about returning object that is contained in the Container-class? I did not get any further information when I tried to compile it with -Xlint:unchecked. What do I make of the error message?

Code that caused the error:

class GenericContainer {

    public static void main(String[] args) {
        Container BookStorage = new Container <Book>();
        Book thejavabook = new Book("The Java book");   
        BookStorage.Store(thejavabook);
    }       
}

class Book {
    private String title;
    Book(String title) {
        this.title = title;
    }
}

class Container <T> {
    private T thing;

    public void Store(T obj) {
        thing = obj;
    }

    public T ReturnIt() {
        return thing;
    }
}
Matthew Woo
  • 1,288
  • 15
  • 28
  • Did you try -Xlint:unchecked? What did it tell you? Usually Eclipse will give more detailed warnings about these things, if you use Eclipse. – Ryan Amos Jan 23 '13 at 20:04
  • 1
    Yes, i did. Sorry if i was not clear on that point - i got the exact same error message when i compiled it with the Xlint:unchecked-command. But as jdb pointed out, i forgot to use in the assignment. Thanks :) – user2005142 Jan 23 '13 at 20:11

2 Answers2

3

Your BookStorage variable should be defined like this:

Container<Book> BookStorage = new Container <Book>();
jdb
  • 4,419
  • 21
  • 21
2

I've rewritten your code to fix the problem and to use java naming standards:

package com.sandbox;

public class Sandbox {

    public static void main(String[] args) {
        Container<Book> bookStorage = new Container<Book>();  //fix for your warning!
        Book theJavaBook = new Book("The Java book");
        bookStorage.store(theJavaBook);
    }
}


class Book {
    private String title;   //this is unused

    Book(String title) {
        this.title = title;
    }
}


class Container<T> {
    private T thing;

    public void store(T obj) {
        thing = obj;
    }

    public T returnIt() {
        return thing;
    }
}

Emphasis on this line:

Container<Book> bookStorage = new Container<Book>();  //fix for your warning!

You forgot to put the <Book> on the left hand side of your assignment.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356