Unchecked assignment java util list to java util list java lang string

Unchecked assignment: ‘java.util.List’ to ‘java.util.Collection’

I am having an adapter where i have two lists one list is for InvestorsList where it comes with the list of investors and the other list is called investorListFull which is used to filter results when searching.

Below is how i have declared the lists

List investorList; List investorListFull;

Below is how the lists are assigned in my recyclerview adapter constructor

public InvestorsAdapter(Context context, List investorList) < this.context = context; this.investorList = investorList; investorListFull = new ArrayList<>(investorList); >

Below is how i am filtering results in investors list

public Filter getInvestorFilter() < return investorFilter; >private final Filter investorFilter = new Filter() < @Override protected FilterResults performFiltering(CharSequence constraint) < ListfilteredList = new ArrayList<>(); if (constraint == null || constraint.length() == 0) < filteredList.addAll(investorListFull); >else < String filterPattern = constraint.toString().toLowerCase().trim(); for (Investor investor : investorListFull) < if (investor.getUsername().toLowerCase().contains(filterPattern)) < filteredList.add(investor); >if (investor.getDateJoined().toLowerCase().contains(filterPattern)) < filteredList.add(investor); >> > FilterResults filterResults = new FilterResults(); filterResults.values = filteredList; return filterResults; > @Override protected void publishResults(CharSequence constraint, FilterResults filterResults) < investorList.clear(); investorList.addAll((List) filterResults.values); notifyDataSetChanged(); >>;

I am getting Unchecked assignment error in publish results investorList.addAll((List) filterResults.values);

Answer

I am getting Unchecked cast error in publish results investorList.addAll((List) filterResults.values);

That’s because you’re doing an unchecked cast. Actually, you’re doing both a checked and an unchecked cast there.

(List) filterResults.values is a checked cast. This means that the Java compiler will insert a checkcast instruction into the bytecode to ensure that filterResults.values (an Object ) really is an instance of List .

Читайте также:  Изучаем typescript 3 pdf

However, investorList.addAll expects a List , not a List . List is a raw type. You can pass a raw-typed List to a method expecting a List ; but this is flagged as unsafe because the compiler can’t guarantee that it really is a List – there is nothing about the List that makes it a “list of Something “, because of type erasure. The compiler can insert a checkcast instruction to ensure it’s a List ; but not one to ensure it’s a List : this fact is unchecked.

What it’s saying with the warning is “there may be something wrong here; I just can’t prove it’s wrong”. If you know for sure – by construction – that filterResults.values really is a List , casting it to List is safe.

You should write the line as:

investorList.addAll((List) filterResults.values);

Note that this will still give you an unchecked cast warning, because it’s still an unchecked cast – you just avoid the use of raw types as well.

If you feel confident in suppressing the warning, declare a variable, so you can suppress the warning specifically on that variable, rather than having to add the suppression to the method or class; and document why it’s safe to suppress there:

@SuppressWarnings("unchecked") // Safe because List listOfInvestors = (List) filterResults.values; investorList.addAll(listOfInvestors);

Источник

How do I fix «The expression of type List needs unchecked conversion. ‘?

If we can’t eliminate the “unchecked cast” warning and we’re sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.

The warning message “unchecked conversion” implies that we should check the conversion before the assignment. To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type.

Unchecked assignment: ‘java.util.List’ to ‘java.util.List’ It means that you try to assign not type safe object to a type safe variable. If you are make sure that such assignment is type safe, you can disable the warning using @SuppressWarnings annotation, as in the following examples.

This is a common problem when dealing with pre-Java 5 APIs. To automate the solution from erickson, you can create the following generic method:

public static List castList(Class clazz, Collection c) < Listr = new ArrayList(c.size()); for(Object o: c) r.add(clazz.cast(o)); return r; > 
List entries = castList(SyndEntry.class, sf.getEntries()); 

Because this solution checks that the elements indeed have the correct element type by means of a cast, it is safe, and does not require SuppressWarnings .

Since getEntries returns a raw List , it could hold anything.

The warning-free approach is to create a new List , then cast each element of the sf.getEntries() result to SyndEntry before adding it to your new list. Collections.checkedList does not do this checking for you—although it would have been possible to implement it to do so.

By doing your own cast up front, you’re «complying with the warranty terms» of Java generics: if a ClassCastException is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.

It looks like SyndFeed is not using generics.

You could either have an unsafe cast and a warning suppression:

@SuppressWarnings("unchecked") List entries = (List) sf.getEntries(); 

or call Collections.checkedList — although you’ll still need to suppress the warning:

@SuppressWarnings("unchecked") List entries = Collections.checkedList(sf.getEntries(), SyndEntry.class); 

Did you write the SyndFeed ?

Does sf.getEntries return List or List ? My guess is it returns List and changing it to return List will fix the problem.

If SyndFeed is part of a library, I don’t think you can remove the warning without adding the @SuppressWarning(«unchecked») annotation to your method.

If you are using Guava and all you want to do is iterate through your values:

for(SyndEntry entry: Iterables.filter(sf.getEntries(), SyndEntry.class)

If you need an actual List you can use

List list = Lists.newArrayList( Iterables.filter(sf.getEntries(), SyndEntry.class)); 
List list = ImmutableList.copyOf( Iterables.filter(sf.getEntries(), SyndEntry.class)); 

Источник

Unchecked assignment on creating an array of lists

Method call causing warning Method being called Warning details Solution 1: Sounds like you have an old version of IntelliJ. This warning really means Java 5.0+ and AFAIK this was changed when IntelliJ supported Java 6 so the warning was there but didn’t say «JDK 5.0 only» (it now has support for Java 8) Solution 2: Having played with super type tokens for this, I don’t think you can make this type-safe without making extra methods to retrieve collections from your cache and verifying if their contents are of the correct type.

Unchecked assignment on creating an array of lists

I’m creating an array of lists of strings like this:

List[] newList = new List[arrayLength]; 

It works but gives the following warning:

You cannot do this without getting a warning, because arrays and generics don’t work well together.

Why should you use an array of lists anyway? Just use a List> .

You say you «don’t need» a flexible arraylist, but who said you should use an ArrayList ? List is an interface, and some implementations don’t allow resizing. For instance, Arrays::asList returns a fixed-sized list.

You should specify your List type (here I use String) in order to solve the warning.

I break it down in steps to simplify understanding:

 List myList = new ArrayList<>(); List innerList = new ArrayList<>(); innerList.add("first value"); innerList.add("second value"); myList.add(innerList); 

If your fixed array is mandatory you can use:

List[] myList = new List[2]; myList[0] = Arrays.asList("Test 1", "Test 2"); myList[1] = Arrays.asList("Test 3", "Test 4"); System.out.println(Arrays.toString(myList)); 

Output — No warnings received

Java — Unchecked assignment warning, And this line: Map map = a.getMap (); gets you a warning now: «Unchecked assignment: ‘java.util.Map to … Code samplepublic void processA(A a) map = a.getMap();>Feedback

Intellij Warning — Generic Unchecked Assignment [duplicate]

Possible Duplicate:
Java Generics , how to avoid unchecked assignment warning when using class hierarchy?

Intellij is giving me the warning below. Not sure how to resolve it, or even if I need to resolve it. The warning details says it only applies to JDK 5, and I am using 6. I am wondering if I need to respond to this, and if so, how?

Method call causing warning

List refObject = cache.getCachedRefObject(cacheKey, List.class); 
public T getCachedRefObject(String objectKey, Class type)
Unchecked Assignment JDK 5.0 only. Signals places where an unchecked warning is issued by the compiler, for example: void f(HashMap map)

Sounds like you have an old version of IntelliJ. This warning really means Java 5.0+ and AFAIK this was changed when IntelliJ supported Java 6 so the warning was there but didn’t say «JDK 5.0 only» (it now has support for Java 8)

Having played with super type tokens for this, I don’t think you can make this type-safe without making extra methods to retrieve collections from your cache and verifying if their contents are of the correct type.

  1. Doing the above, which seems laborious
  2. Suppress the unchecked cast in client code if you know it’s correct.
  3. Replace the client code with List refObject = cache.getCachedRefObject(cacheKey, List.class);

The only type-safe variant of these is 3., in that it prevents you from doing operations that the compiler can’t prove are type-safe. The obvious downside is that you might want to do some of these operations anyway.

Generics — Unchecked assignment: ‘anonymous, Unchecked assignment: ‘anonymous java.util.Iterator’ to ‘java.util.Iterator‘ Now I could just ignore the warning or fill an …

How to remove unchecked assignment warning in hibernate generics

I am implementing the generics to access the data in hibernate using following code:

public static List get(Class clazz,Map map) throws GenericDataAccessException < Listdata = null; Session session = null; try < session = HibernateUtilities.getSession(); session.beginTransaction(); Criteria cr = session.createCriteria(clazz.getName()); Iterator itr = map.entrySet().iterator(); while(itr.hasNext())< Map.Entry entry = ( Map.Entry)itr.next(); cr.add(Restrictions.eq(entry.getKey().toString(),entry.getValue())); >data = cr.list(); > catch (Exception e) < logger.debug("Hibernate Error::" + e.toString()); throw new GenericDataAccessException(e.getMessage()); >finally < if(session != null) < session.close(); >> return data; > 

But at the line data = cr.list(); unchecked assignment warning is shown. How remove this warning without suppress warning ? If I change the return type from generic list to list then warning is removed but in that case I get the warning in class from where calling this method.

Firstly, there are some problems in your code

  1. You don’t commit and rollback a transaction.
  2. You don’t need to log an exception in a low level method, just rethrow it.
  3. If you log an exception you should do it this way logger.debug(«Hibernate Error», e);
  4. You should rethrow an exception this way throw new GenericDataAccessException(e);
  5. You don’t need data just do return cr.list();

There is no way to remove an » unchecked assignment» warning , because of Criteria has a list() declaration with return type List not List .

List list() throws HibernateException; 

So just use suggested by @TimBiegeleisen @SuppressWarnings(«unchecked») . But only in one low level place! Not above all kinds of get() methods. So you need to have a more complex architecture of your generics with one get() method.

  • Firstly, you can separate working with a session and transactions in the separate utility method. Something like this HibernateSessionFactory#doInTransaction().
  • The second step is configure request parameters outside a request method (something likes your map ) like this HibernateRequest#list().

Generics — Unchecked assignment warning in Java, Add a comment. 1. It’s because your OperationsFactory returns an Operation rather than a properly genericized Operation, so if you assign it …

Getting rid of unchecked assignment

I have the following piece of code

1. final List> maps = . 2. final Map[] arrMaps = maps.toArray(new Map[maps.size()]); 3. getNamedParameterJdbcTemplate().batchUpdate(. arrMaps); 

On line 3 I get an Unchecked assignement . How can I get rid of it?

I do not want to suppress the warning and I can’t figure out how to fix it. If a try to cast or convert something, the warning appears somewhere else.

I couldn’t find a way to get rid of that unchecked exception by playing with types and casts. Instead I used MapSqlParameterSource[] as a source of data for my batchUpdate .

Java — getting rid of unchecked assignment, I have the following piece of code 1. final List maps = 2. final Map[] arrMaps = maps.toArray(new …

Источник

Оцените статью