Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

java uses unsafe operations error in hashmap and arraylist

I was hoping to get a quick hand I have never encountered this error before. I think it is something in this part of my code but not sure :

public class ePortfolio {
protected HashMap <String,ArrayList<Integer>>map;
protected ArrayList <investment>list;
public ePortfolio(){
    list=new ArrayList();
    map= new HashMap();        
}    

if there is anything more I need to add ill be happy to just don’t want to clutter the page .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’ll guess as you’ve not given much detail:

The problem is that you are assigning a raw object, new ArrayList() to a genericized reference variable, ArrayList <investment> list.

You should instead let the compiler infer the generic parameters of your collection objects. Insert the empty angle-brackets <>.

public class ePortfolio {
    protected HashMap < String , ArrayList < Integer > > map ;
    protected ArrayList < Investment > list ;

    // Constructor
    public ePortfolio(){
        list = new ArrayList<>() ;  // ☚ Insert empty angles to ask compiler to infer the parameterized type. 
        map = new HashMap<>() ;        
    }    

By the way, it is usually best to refer to the most general type that meets your needs. This way you can later swap out the more specific concrete type without breaking any code.

So if Map and List meet your needs, use those.

public class ePortfolio {
    protected Map < String , List < Integer > > map ;
    protected List < Investment > list ;

    // Constructor
    public ePortfolio(){
        list = new ArrayList<>() ;  // ☚ Insert empty angles to ask compiler to infer the parameterized type. 
        map = new HashMap<>() ;        
    }    

As commented, see What is a raw type and why shouldn’t we use it?. And see tutorial on Generics by Oracle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading