001/** 002 * Copyright 2011-2015 John Ericksen 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.parceler; 017 018import java.util.ArrayList; 019import java.util.List; 020 021/** 022 * @author John Ericksen 023 */ 024public final class IdentityCollection { 025 026 private static final Object RESERVATION = new Object(); 027 private final List<Object> values = new ArrayList<Object>(); 028 029 public IdentityCollection() { 030 put(null); 031 } 032 033 public boolean containsKey(int id){ 034 return id < values.size(); 035 } 036 037 public int reserve() { 038 return put(RESERVATION); 039 } 040 041 public boolean isReserved(int id) { 042 return values.get(id) == RESERVATION; 043 } 044 045 public void put(int id, Object input){ 046 if(values.size() > id) { 047 values.remove(id); 048 } 049 values.add(id, input); 050 } 051 052 public int put(Object input) { 053 values.add(input); 054 return values.size() - 1; 055 } 056 057 @SuppressWarnings("unchecked") 058 public <T> T get(int id){ 059 return (T) values.get(id); 060 } 061 062 public int getKey(Object input) { 063 for(int i = 0; i < values.size(); i++) { 064 if(values.get(i) == input) { 065 return i; 066 } 067 } 068 return -1; 069 } 070}