001package jmri.util; 002 003import javax.annotation.Nonnull; 004 005/** 006 * Useful array methods. 007 * 008 * @author Bob Jacobsen 2022 009 */ 010public final class ArrayUtil { 011 012 /** 013 * Reverse an array of objects. 014 * <p> 015 * Not suitable for primitive types. 016 * 017 * @param <T> the Type of the array contents 018 * @param elements the array 019 * @return the reversed array 020 */ 021 public static <T> T[] reverse(@Nonnull T[] elements) { 022 assert (elements != null); 023 var results = java.util.Arrays.copyOf(elements, elements.length); 024 for (int i = 0; i < elements.length; i++) { 025 results[i] = elements[elements.length-i-1]; 026 } 027 return results; 028 } 029 030 /** 031 * Reverse an array of ints. 032 * 033 * @param elements the array 034 * @return the reversed array 035 */ 036 public static int[] reverse(@Nonnull int[] elements) { 037 assert (elements != null); 038 var results = new int[elements.length]; 039 for (int i = 0; i < elements.length; i++) { 040 results[i] = elements[elements.length-i-1]; 041 } 042 return results; 043 } 044 045 /** 046 * Reverse an array of longs. 047 * 048 * @param elements the array 049 * @return the reversed array 050 */ 051 public static long[] reverse(@Nonnull long[] elements) { 052 assert (elements != null); 053 var results = new long[elements.length]; 054 for (int i = 0; i < elements.length; i++) { 055 results[i] = elements[elements.length-i-1]; 056 } 057 return results; 058 } 059 060 /** 061 * Reverse an array of doubles. 062 * 063 * @param elements the array 064 * @return the reversed array 065 */ 066 public static double[] reverse(@Nonnull double[] elements) { 067 assert (elements != null); 068 var results = new double[elements.length]; 069 for (int i = 0; i < elements.length; i++) { 070 results[i] = elements[elements.length-i-1]; 071 } 072 return results; 073 } 074 075 /** 076 * Reverse an array of floats. 077 * 078 * @param elements the array 079 * @return the reversed array 080 */ 081 public static float[] reverse(@Nonnull float[] elements) { 082 assert (elements != null); 083 var results = new float[elements.length]; 084 for (int i = 0; i < elements.length; i++) { 085 results[i] = elements[elements.length-i-1]; 086 } 087 return results; 088 } 089 090 /** 091 * Reverse an array of booleans. 092 * 093 * @param elements the array 094 * @return the reversed array 095 */ 096 public static boolean[] reverse(@Nonnull boolean[] elements) { 097 assert (elements != null); 098 var results = new boolean[elements.length]; 099 for (int i = 0; i < elements.length; i++) { 100 results[i] = elements[elements.length-i-1]; 101 } 102 return results; 103 } 104 105 // private transient final static Logger log = LoggerFactory.getLogger(ArrayUtil.class); 106}