当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
计算机二级辅导:合并字符串数组的实现
发布时间:2011/6/25 18:33:07 来源:城市学习网 编辑:admin
  看源代码:
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  /**
  * 合并多个字符串数组。
  *
  *     class T {
  public static void main(String[] args) {
  String[] s1 = { "1", "2" };
  String[] s2 = { "3", "4" };
  String[] s3 = new String[s1.length + s2.length];
  System.arraycopy(s1, 0, s3, 0, s1.length);
  System.arraycopy(s2, 0, s3, s1.length, s2.length);
  System.out.println(Arrays.toString(s3));
  // 方法2,用List
  List<String> list = new ArrayList<String>();
  for(String s : s1) {
  list.add(s);
  }
  for(String s : s2) {
  list.add(s);
  }
  String[] s4 = list.toArray(new String[0]);
  System.out.println(Arrays.toString(s4));
  }
  }
  原理很简单,新建一个能够容纳所有数据的新数组,然后根据长度复制过去
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved