`
java-mans
  • 浏览: 11417649 次
文章分类
社区版块
存档分类
最新评论

将整个 ArrayList 复制到兼容的一维 Array

 
阅读更多
Code:
  1. usingSystem;
  2. usingSystem.Collections;
  3. publicclassSamplesArrayList{
  4. publicstaticvoidMain(){
  5. //CreatesandinitializesthesourceArrayList.
  6. ArrayListmySourceList=newArrayList();
  7. mySourceList.Add("three");
  8. mySourceList.Add("napping");
  9. mySourceList.Add("cats");
  10. mySourceList.Add("in");
  11. mySourceList.Add("the");
  12. mySourceList.Add("barn");
  13. //Createsandinitializestheone-dimensionaltargetArray.
  14. String[]myTargetArray=newString[15];
  15. myTargetArray[0]="The";
  16. myTargetArray[1]="quick";
  17. myTargetArray[2]="brown";
  18. myTargetArray[3]="fox";
  19. myTargetArray[4]="jumped";
  20. myTargetArray[5]="over";
  21. myTargetArray[6]="the";
  22. myTargetArray[7]="lazy";
  23. myTargetArray[8]="dog";
  24. //DisplaysthevaluesofthetargetArray.
  25. Console.WriteLine("ThetargetArraycontainsthefollowing(beforeandaftercopying):");
  26. PrintValues(myTargetArray,'');
  27. //CopiesthesecondelementfromthesourceArrayListtothetargetArray,startingatindex7.
  28. mySourceList.CopyTo(1,myTargetArray,7,1);
  29. //DisplaysthevaluesofthetargetArray.
  30. PrintValues(myTargetArray,'');
  31. //CopiestheentiresourceArrayListtothetargetArray,startingatindex6.
  32. mySourceList.CopyTo(myTargetArray,6);
  33. //DisplaysthevaluesofthetargetArray.
  34. PrintValues(myTargetArray,'');
  35. //CopiestheentiresourceArrayListtothetargetArray,startingatindex0.
  36. mySourceList.CopyTo(myTargetArray);
  37. //DisplaysthevaluesofthetargetArray.
  38. PrintValues(myTargetArray,'');
  39. }
  40. publicstaticvoidPrintValues(String[]myArr,charmySeparator){
  41. for(inti=0;i<myArr.Length;i++)
  42. Console.Write("{0}{1}",mySeparator,myArr[i]);
  43. Console.WriteLine();
  44. }
  45. }
  46. /*
  47. Thiscodeproducesthefollowingoutput.
  48. ThetargetArraycontainsthefollowing(beforeandaftercopying):
  49. Thequickbrownfoxjumpedoverthelazydog
  50. Thequickbrownfoxjumpedoverthenappingdog
  51. Thequickbrownfoxjumpedoverthreenappingcatsinthebarn
  52. threenappingcatsinthebarnthreenappingcatsinthebarn
  53. */

还记得当初我刚出去面试的时候,一个经典的小算法题目,我是用的最菜鸟最原始的方式,以下是我写的代码

Code:
  1. usingSystem.Collections;
  2. namespace面试题目
  3. {
  4. class数组操作
  5. {
  6. privatestringname;
  7. ///<summary>
  8. ///产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。
  9. ///</summary>
  10. publicvoidinsertArr()
  11. {
  12. //定义一个长度为100的数组
  13. int[]arr=newint[100];
  14. //定义动态数组--方便储值
  15. ArrayListlist=newArrayList();
  16. Randomran=newRandom();
  17. //当动态数组个数不满100时,循环生成随机数
  18. while(list.Count<100)
  19. {
  20. intnum=ran.Next(1,101);
  21. //如果产生的随机数不包含在动态数组list中(不重复),就添加进list
  22. if(!list.Contains(num))
  23. {
  24. list.Add(num);
  25. }
  26. }
  27. //通过循环,将动态数组list中的元素复制给数组arr
  28. for(inti=0;i<100;i++)
  29. {
  30. arr[i]=(int)list[i];
  31. }
  32. }
  33. }
  34. }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics