很简单的数组和集合操作. 在打印出结果之前, 请先预料一下, 注意一下注释和代码中红色的部分. 欢迎给出您的看法. 谢谢!
java 代码
- public static void main(String[] args) {
- LabelValueBean[] lvBeans = new LabelValueBean[3];
- lvBeans[0] = new LabelValueBean("l0","v0");
- lvBeans[1] = new LabelValueBean("l1","v1");
- lvBeans[2] = new LabelValueBean("l2","v2");
- Map<String, LabelValueBean> arrMap = new HashMap<String, LabelValueBean>();
- arrMap.put("lv0", lvBeans[0]);
- arrMap.put("lv1", lvBeans[1]);
- arrMap.put("lv2", lvBeans[2]);
- for(int i = 0;i < lvBeans.length;i ++) {
- logInfo("before: " + lvBeans[i].getLabel());
- }
- /**
- *Collection 的 Object[] toArray() 方法有这样的注释:(注意加粗部分)
- *
- * Returns an array containing all of the elements in this collection. If
- * the collection makes any guarantees as to what order its elements are
- * returned by its iterator, this method must return the elements in the
- * same order.<p>
- *
- * The returned array will be "safe" in that no references to it are
- * maintained by this collection. (In other words, this method must
- * allocate a new array even if this collection is backed by an array).
- * The caller is thus free to modify the returned array.<p>
- *
- * This method acts as bridge between array-based and collection-based
- * APIs.
- *
- * @return an array containing all of the elements in this collection
- */
- Object[] lv1 = (Object[]) arrMap.values().toArray();
- for(int i = 0;i < lv1.length;i ++) {
- LabelValueBean lv = (LabelValueBean)lv1[i];
- lv.setLabel("++");
- logInfo("Modifying: " + lv.getLabel());
- }
- for(int i = 0;i < lvBeans.length;i ++) {
- logInfo("after: " + lvBeans[i].getLabel());
- }
- }
- public static void logInfo(String str) {
- System.out.println("-----Info:\n " + str);
- }
另: LabelValueBean 定义
java 代码
- public class LabelValueBean {
- private String label;
- private String value;
- public LabelValueBean() {
- }
- public LabelValueBean(String label, String value) {
- this.label = label;
- this.value = value;
- }
- public String getLabel() {
- return label;
- }
- public void setLabel(String label) {
- this.label = label;
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- }