1 package org.jibx.binding.util; 2 3 4 8 9 public class StringArray 10 { 11 12 private final String [] m_list; 13 14 22 public StringArray(String [] list) { 23 validateArray(list); 24 m_list = list; 25 } 26 27 35 public StringArray(String [] list, StringArray base) { 36 validateArray(list); 37 m_list = mergeArrays(list, base.m_list); 38 } 39 40 49 public StringArray(StringArray array1, StringArray array2) { 50 m_list = mergeArrays(array1.m_list, array2.m_list); 51 } 52 53 61 private String [] mergeArrays(String [] list1, String [] list2) { 62 String [] merge = new String [list1.length + list2.length]; 63 int fill = 0; 64 int i = 0; 65 int j = 0; 66 while (i < list1.length && j < list2.length) { 67 String comp = list1[i]; 68 int diff = list2[j].compareTo(list1[i]); 69 if (diff > 0) { 70 merge[fill++] = list1[i++]; 71 } else if (diff < 0) { 72 merge[fill++] = list2[j++]; 73 } else { 74 throw new IllegalArgumentException 75 ("Duplicate values in arrays"); 76 } 77 } 78 if (i < list1.length) { 79 System.arraycopy(list1, i, merge, fill, list1.length-i); 80 } 81 if (j < list2.length) { 82 System.arraycopy(list2, j, merge, fill, list2.length-j); 83 } 84 return merge; 85 } 86 87 93 private void validateArray(String [] list) { 94 if (list.length > 0) { 95 String last = list[0]; 96 int index = 0; 97 while (++index < list.length) { 98 String comp = list[index]; 99 int diff = last.compareTo(comp); 100 if (diff > 0) { 101 throw new IllegalArgumentException 102 ("Array values are not ordered"); 103 } else if (diff < 0) { 104 last = comp; 105 } else { 106 throw new IllegalArgumentException 107 ("Duplicate values in array"); 108 } 109 } 110 } 111 } 112 113 119 public String get(int index) { 120 return m_list[index]; 121 } 122 123 133 public int indexOf(String value) { 134 int base = 0; 135 int limit = m_list.length - 1; 136 while (base <= limit) { 137 int cur = (base + limit) >> 1; 138 int diff = value.compareTo(m_list[cur]); 139 if (diff < 0) { 140 limit = cur - 1; 141 } else if (diff > 0) { 142 base = cur + 1; 143 } else { 144 return cur; 145 } 146 } 147 return -1; 148 } 149 150 155 public int size() { 156 return m_list.length; 157 } 158 } | Popular Tags |