LoginSignup
1
1

More than 5 years have passed since last update.

文字列 と 配列,List の相互変換

Posted at
変換前 変換後
List<Character> String
String ArrayList<Character>
char[] String
String char[]
StringBuilder char[] (コピー)

もっと楽な方法ないのかな。

ConvertStringArrayList.java
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConvertStringArrayList {
    public static void main(String[] args){
        ArrayList<Character> list = new ArrayList<Character>(Arrays.asList('h','e','l','l','o'));
        String str = "hello";
        char[] arr = {'h','e','l','l','o'};

        // ArrayList<Character> -> String
        if (toStr(list).equals(str)) System.out.println("OK");
        else System.out.println("not OK");
        // String -> ArrayList<Character>
        if (toList(str).equals(list)) System.out.println("OK");
        else System.out.println("not OK");
        // char[] -> String
        if (new String(arr).equals(str)) System.out.println("OK");
        else System.out.println("not OK");
        // String -> char[]
        if (Arrays.equals(toArr(str),arr)) System.out.println("OK");
        else System.out.println("not OK");

        // StringBuilder -> char[] (コピー)
        StringBuilder sb = new StringBuilder("hello");
        char[] arr3 = new char[5];
        sb.getChars(0,sb.length(),arr3,0);
        if (Arrays.equals(arr3,arr)) System.out.println("OK");
        else System.out.println("not OK");
    }   

    public static String toStr(List<Character> list){
        // List<Character> -> String
        int l = list.size();
        char[] cs = new char[l];
        Iterator<Character> iter = list.iterator();
        for (int i=0;i<l;i++) cs[i] = iter.next();
        return new String(cs);
    }   

    public static ArrayList<Character> toList(String str){
        // String -> ArrayList<Character>
        int l = str.length();
        ArrayList<Character> list = new ArrayList<Character>();
        for (int i=0;i<l;i++) list.add(str.charAt(i));
        return list;
    }   

    public static char[] toArr(String str){
        // String -> char[]
        int l = str.length();
        char[] arr = new char[l];
        for (int i=0;i<l;i++) arr[i] = str.charAt(i);
        return arr;
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1