Chat-Applikation/src/utils/ArrayHelper.java

71 lines
2.1 KiB
Java

/*
* Copyright (C) 2021 eichehome
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package utils;
/**
*
* @author eichehome
* @param <T> Type des Arrays, mit dem gearbeitet wird.
*/
public class ArrayHelper<T> {
public T[] push(T element, T[] array) {
if (array != null) {
T[] temp = new T[1 + array.length];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
temp[temp.length - 1] = element;//Letzter eintrag
array = temp;
} else {
T[] temp = new T[1];
temp[temp.length - 1] = element;
array = temp;
}
return array;
}
public T pop(T element, T[] array) throws IllegalArgumentException {
if (array != null) {
int index = getIndex(element, array);
T result = array[index];
T[] temp;
temp = new T[array.length - 2];
for (int i = 0; i < index; i++) {
temp[i] = array[i];
}
for (int i = ++index; i < temp.length; i++) {
temp[i - 1] = array[i];
}
return result;
} else {
throw new IllegalArgumentException("Element not found");
}
}
int getIndex(T match, T[] array) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(match)) {
result = i;
break;
}
}
return result;
}
}