Javaã§ããã¾ã«ãªã¹ãã¨é
åãå¤æããããã³ãã¼ãããããã¨ããããã¾ãã
ã§ãæå¤ã¨ãããã¨ãããã³ã«å¿ãã¦ãã¾ãã®ã§ããã£ã¨ã¾ã¨ãã¦ã¿ã¾ããã
ï¼è§£èª¬ãåãããããããããã«ãã¸ã§ããªã¯ã¹ã使ç¨ãã¦ãã¾ããï¼
ãªã¹ã ãã é åï¼å¤æï¼
public static String[] convert(List<String> list){ return list.toArray(new String[list.size()]); }
toArray ã®å¼æ°ã¯ãnew String[0]ã§ããã¾ãã¾ãããã
ããããããµã¤ãºã確å®ãã¦ããå ´åã¯ããã®ãµã¤ãºã§é
åãä½ã£ã¦ãããæ¹ãããããªããå¹çãè¯ããªãã¾ãã
Listから配列への無駄のない変換 - 地平線に行く
ãªã¹ã ãã ãªã¹ãï¼ã³ãã¼ï¼
public static List<String> copy(List<String> list){ return new ArrayList<String>(list); }
Java Collections Framework ã®ã¯ã©ã¹*1ã«ã¯ãå¿
ãCollection åã®å¼æ°ãæã¤ã³ã³ã¹ãã©ã¯ã¿ãå®è£
ããã¦ããã®ã§ãããã使ãã°ç°¡åã«ã³ãã¼ã§ãã¾ãã
é å ãã ãªã¹ãï¼å¤æï¼
public static List<String> convert(String[] array){ return new ArrayList<String>(Arrays.asList(array)); }
Arrays.asList(T...) ã ãã§ããªã¹ãã«å¤æã§ãã¾ããã以ä¸ã®å¶éããããã¾ãã
- é åã¨é£åããï¼é åãå¤æ´ããããªã¹ãã«åæ ãããããªã¹ããå¤æ´ãããé åã«åæ ãããï¼
- 追å (add, addAll)ãåé¤(remove, clear) ãã§ããªãï¼UnsupportedOperationException ãã¹ãã¼ãããï¼
ãã®ãããArrayListã«ã³ãã¼ãã¦ããã®ãç¡é£ã§ãã
éã«ãé£åãã¦ããã¾ããªãã®ã§ããã°ã以ä¸ã®ããæ¹ã§ä¸çºå¤æãããã¨ãå¯è½ã§ãã
List<String> list = Arrays.asList("ABC", "DEF", "GHI");
é å ãã é åï¼ã³ãã¼ï¼
public static String[] copy(String[] array){ return Arrays.copyOf(array, array.length); }
Arrays.copyOf 㯠System.arraycopy ã®ã©ããã¼ã§ãã
æ°ããé
åãä½ã£ã¦ã³ãã¼ããã®ã§ããã°ãArrays.copyOf ã®æ¹ãç°¡åã§ãã
ã¸ã§ããªã¯ã¹ç
åèã¾ã§ã«ãä»åã®æ±ç¨ã¯ã©ã¹ãä½ã£ã¦ã¿ã¾ããã
ï¼ã¸ã§ããªã¯ã¹ã«å¯¾å¿ããå¼æ°ãCollectionã«ãã¦ãã¾ãï¼
public class ArrayListUtils { /** * @see Collection#toArray(Object[]) */ public static <T> T[] convert(Collection<T> c, T[] array){ return c.toArray(array); } /** * @see ArrayList(Collection) * @see Arrays#asList(Object...) */ public static <T> List<T> convert(T[] array){ return new ArrayList<T>(Arrays.asList(array)); } /** * @see Collection */ public static <T> List<T> copy(Collection<T> c){ return new ArrayList<T>(c); } /** * @see Arrays#copyOf(Object[], int) */ public static <T> T[] copy(T[] array){ return Arrays.copyOf(array, array.length); } }
ã³ã¬ã¯ã·ã§ã³ããé åã¸ã®å¤æã¡ã½ãããã¡ãã£ã¨ãã¾ãã¡ã»ã»ã»ã
*1:List ã SetãMapãªã©