001/* 002 * Copyright 2023 the original author or authors. 003 * <p> 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 * <p> 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * <p> 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 de.cuioss.tools.collect; 017 018import java.io.Serializable; 019import java.util.ArrayList; 020import java.util.Collection; 021import java.util.Collections; 022import java.util.List; 023 024import lombok.EqualsAndHashCode; 025import lombok.Getter; 026import lombok.ToString; 027 028/** 029 * <h2>Overview</h2> Default implementation of {@link PartialCollection} based 030 * on {@link ArrayList}. 031 * <h3>Usage</h3> 032 * <p> 033 * See {@link PartialArrayList#of(List, int)} 034 * </p> 035 * 036 * @param <T> at least {@link Serializable} 037 */ 038@EqualsAndHashCode(callSuper = true) 039@ToString(callSuper = true) 040public class PartialArrayList<T extends Serializable> extends ArrayList<T> implements PartialCollection<T> { 041 042 private static final long serialVersionUID = -7548645400982124555L; 043 044 @Getter 045 private final boolean moreAvailable; 046 047 /** 048 * Default constructor. 049 * 050 * @param list the list of entities to store. 051 * @param moreAvailable the flag to store. 052 */ 053 public PartialArrayList(Collection<T> list, boolean moreAvailable) { 054 super(list); 055 this.moreAvailable = moreAvailable; 056 } 057 058 /** 059 * Static constructor for an empty instance. 060 * 061 * @param <T> 062 * @return an empty {@link PartialArrayList}. 063 */ 064 public static <T extends Serializable> PartialArrayList<T> emptyList() { 065 return new PartialArrayList<>(Collections.emptyList(), false); 066 } 067 068 /** 069 * Convenience method for creating a {@link PartialArrayList} as sublist for the 070 * given collection with setting the {@link PartialCollection#isMoreAvailable()} 071 * automatically 072 * 073 * @param full the complete List to be wrapped, may be larger than the limit. 074 * If so, a sublist will be used. 075 * @param limit to be checked against 076 * 077 * @param <T> identifying the type of contained elements 078 * @return a newly created {@link PartialArrayList}. 079 */ 080 public static <T extends Serializable> PartialArrayList<T> of(List<T> full, int limit) { 081 if (MoreCollections.isEmpty(full)) { 082 return emptyList(); 083 } 084 var actualSize = full.size(); 085 if (actualSize <= limit) { 086 return new PartialArrayList<>(full, false); 087 } 088 return new PartialArrayList<>(full.subList(0, limit), true); 089 } 090 091}