How to limit char size in string stored as ArrayList elements in Java?

There is currently an ArrayList line in Java, but I would like to trim (or limit) the number of characters in each line to 20. I could not find a way to do this.

Example:

 "hello this is one of the descriptions in an array list, please limit me to 20" 

should become:

 "hello this is one of" 
+4
source share
5 answers

Some possible ways:

  • Extend the ArrayList and override its add(...) methods. I do not like it.
  • Wrap your ArrayList and in public methods that add or modify its contents, limit the number of characters. I like this idea more!
  • Edit: Or not have an ArrayList<String> , but instead an ArrayList<MyCustomClass> , where set or MyCustomClass methods or methods trim Strings as needed. I like that too!
+3
source

In a method that adds lines:

 public void addString(String str) { String truncated = str != null ? str.substring(0, 20) : null; strings.add(truncated); } 
+2
source

You do this using String.substring () . Example:

 String str = "hello this is one of the descriptions in an array list, please limit me to 20"; String str20 = str.substring(0, 20); 
0
source

Assuming this is an existing list that you want to modify:

 public static void truncate20(List<String> strs) { for (ListIterator<String> iter = strs.listIterator(); iter.hasNext();) { String str = iter.next(); if (str.length() > 20) { iter.set(str.substring(0, 20)); } } } 

Creating a new list is simple enough - just add each iteration.

If you want to do this on the insert, I suggest you write a class for it that * does not extend List . Just give the operation you need that makes sense.

0
source

You can also just have an ArrayList for a custom class, which is an array of 20 characters. The disadvantage, of course, is that you are essentially reprofiling the Java String class

0
source

Source: https://habr.com/ru/post/1402354/


All Articles