0

I've been handed some code to check SMS data, and there is a filter function using a vector cast, that is now causing the compile warning:

Unchecked cast: 'java.lang.Object' to 'java.util.Vector<xxx.Event>'

at this location:

values = (Vector<Event>) results.values;
                                ^
required: Vector<Event>
found:    Object

The code snippet is as follows:

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.count != 0) {
                values = (Vector<Event>) results.values;
                notifyDataSetChanged();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence smsType) {
            FilterResults results = new FilterResults();
            Vector<Event> eventList = new Vector<>();

            if (smsType.equals("ALL")) {
                results.values = allEvents;
                results.count = allEvents.size();
                return results;
            }
            for (Event event : allEvents) {
                if (event.getType().toString().equals(smsType)) {
                    eventList.add(event);
                }
            }
            results.values = eventList;
            results.count = eventList.size();
            return results;
        }
    };
}

I have already looked around at various SO solutions such as: this, this, this, this, this and this. But I must admit they have only caused more confusion.

In addition there are some suggestions to use an ArrayList instead of a Vector, but that Vectors have the advantage of being synchronized unlike ArrayLists. I have no idea if this is of any importance here.

And no, I don't want to @SuppressWarnings, but rather try to understand and resolve the problem cleanly using Java 8.

Community
  • 1
  • 1
not2qubit
  • 14,531
  • 8
  • 95
  • 135

1 Answers1

1

java.util.Vector shouldn't be used at all, because it's been obsolescent for nineteen years. It carries non-collections cruft we don't need. Use a synchronized or concurrent list if you need concurrency. Banish Vector (and Hashtable) from your toolbox.

(Vector<Event>) and other generic casts will always be unchecked because generic types are not reifiable. You need a runtime type token, an object of type Class<T>, and use its cast method to do a generic cast, but it's probably easier to get over your "I don't want to @SuppressWarnings" bigotry and use that annotation properly, as documented in Effective Java, by Joshua Bloch.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10