Java split Arraylist into smaller ArrayLists
arraylist, java
Solution
Simply use `List<String>` as the type of `crawl_list1`.
That's just an application of the general rule of "code against the interface".
There's really no good reason to require the return value of `subList` to be an `ArrayList` (and it doesn't make sense as `subList` returns a view onto the original `ArrayList`).
If you absolutely need `ArrayList` objects, then you need to copy the content into new `ArrayList` objects:
ArrayList<String> crawl_list1 = new ArrayList<String>(tmp.subList(0, start));
ArrayList<String> crawl_list2 = new ArrayList<String>(tmp.subList(start+1, middle));
ArrayList<String> crawl_list3 = new ArrayList<String>(tmp.subList(middle+1, end));
Problem
I have an ArrayList with a size of `258` Now i wish to split this into three different ArrayLists for this i have created the following code: ``` Integer start = (int) Math.floor((sitesToSearch.size() / 3)); Integer middle = (int) Math.floor((sitesToSearch.size() / 2)); Integer end = (int) Math.floor((sitesToSearch.size() / 1)); ArrayList<String> crawl_list1 = (ArrayList<String>)tmp.subList(0, start); ArrayList<String> crawl_list2 = (ArrayList<String>)tmp.subList(start+1, middle); ArrayList<String> crawl_list3 = (ArrayList<String>)tmp.subList(middle+1, end); ``` Sadly this throws the following error: ``` Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList$SubList cannot be cast to java.util.ArrayList ``` So how can i devide it into three smaller ArrayList ``` tmp declaration: public ArrayList<String> getExternalLinks(ArrayList<String> rootDomains){ ArrayList<String> result = new ArrayList<String>(); Document doc = null; /* * Check if root is valid * Find search the site for internal links */ for (String root : rootDomains) { if (!(root == null) || !root.isEmpty() ||!root.contains("#")) { try { doc = Jsoup.connect(root) .userAgent("Mozilla") .get(); result.addAll(findExternalLinks(findInternalLinks(doc,root),root)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println(result.size()); return result; ``` }