Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<Object> getAggregateTree(List<Object> items, int maxPerList) {
        if (items == null) {
            throw new IllegalArgumentException("items can not be null");
        }
        if (maxPerList < 2) {
            throw new IllegalArgumentException("maxPerList can not be less than 2");
        }

        if (items.size() > maxPerList) {
            return (recursiveAggregateTree(items, maxPerList));
        } else {
            return new ArrayList<Object>(items);
        }
    }

    private static List<Object> recursiveAggregateTree(List<Object> items, int maxPerList) {
        if (items.size() > maxPerList) {
            ArrayList<Object> aggregateList = new ArrayList<Object>(maxPerList);
            ArrayList<Object> childList = null;

            for (Object item : items) {
                if (childList == null || childList.size() == maxPerList) {
                    childList = new ArrayList<Object>(maxPerList);
                    aggregateList.add(childList);
                }
                childList.add(item);
            }
            childList.trimToSize();

            aggregateList.addAll(recursiveAggregateTree(aggregateList, maxPerList));

            aggregateList.trimToSize();

            return aggregateList;
        } else {
            // This is a safe blind cast since only subsequent calls of this method will end up here
            // and this method always uses ArrayList<Object>
            return items;
        }
    }
}