Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java safe List

farenda 2015-07-02 0

Problem:

Source of Java ClassCastException sometimes can be hard to find. In such situation type safe List may be really helpful. In this tutorial you will learn how to find ClassCastException using Java type safe List!

Solution:

The following, simplified, Java example shows the ClassCastException issue and how Collections.checkedList(List, type) helps to solve it:

package com.farenda.java;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CollectionsCheckedList {

    public static void main(String[] args) {
        List<String> items = new LinkedList<>();
        Collections.addAll(items, "java", "clojure", "python", "scala");
        System.out.println("Items: " + items);

        addItemInsecurely(items);
        System.out.println("Insecure items: " + items);

        List<String> typeSafe = Collections.checkedList(items, String.class);
        addItemInsecurely(typeSafe);
        System.out.println("No new insecure items!");
    }

    // Add by reflection, 3rd party lib or other insecure way:
    private static void addItemInsecurely(List items) {
        int wrongTypeItem = items.size();
        System.out.println("Adding item: " + wrongTypeItem);
        items.add(wrongTypeItem);
    }
}

In the example we expect a list to be of type String, and then add an integer there is some insecure way. It often happens when a bunch of frameworks are used. This may result in adding an element of different type and ClassCastException may occur much more later in execution flow and be hard to diagnose. Using Collections.checkedList() we can trigger ClassCastException as soon as item of wrong type is inserted into the collection!

As you can seed, when run, the above Java code immediately prevents addition of unsafe element:

Items: [[java, clojure, python, scala]]
Adding item: 4
Insecure items: [[java, clojure, python, scala, 4]]
Adding item: 5
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String
      at java.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
      at java.util.Collections$CheckedCollection.add(Collections.java:3080)
      at com.farenda.java.CollectionsCheckedList.addItemInsecurely(CollectionsCheckedList.java:26)
      at com.farenda.java.CollectionsCheckedList.main(CollectionsCheckedList.java:18)

java.util.Collections has checked methods for different types of Java collections:

  • Collection<E> checkedCollection(Collection<E> c, Class<E> type)
  • Queue<E> checkedQueue(Queue<E> queue, Class<E> type) since Java 8
  • Set<E> checkedSet(Set<E> s, Class<E> type)
  • SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type)
  • NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type) since Java 8
  • List<E> checkedList(List<E> list, Class<E> type)
  • Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)
  • SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
  • NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m, Class<K> keyType, Class<V> valueType) since Java 8

They all work in the same way and can be really helpful. Simple and may save the day! ;-)

Share with the World!
Categories Java Tags java-collections
Previous: Java binary search comparator
Next: Pomodoro technique

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored