Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class Main { @SuppressWarnings("unchecked") public static <T> List<T> sortedIfPossible(Collection<T> collection) { List<T> result = new ArrayList<T>(collection); try { Collections.sort((List) result); } catch (ClassCastException e) { // unable to sort, just return the copy } return result; } }