Вопрос

Я написал здесь страницу об использовании массивов как полноценных объектов со своими собственными методами вместо того, чтобы полагаться на вспомогательные классы, такие как Arrays, Arrays и ArrayUtils.

ints.sort(); // instead of Arrays.sort(ints);
// instead of int[] onemore = ArrayUtils.add(ints, 8);
int[] onemore = ints.add(8); 

Я уверен, что я не первый с этой идеей, но мне было трудно найти других, кто писал об этом раньше.

Может ли кто-нибудь помочь мне с некоторыми ссылками по этой теме?

Можете ли вы добавить комментарии, если у вас есть ссылка на то, почему это плохая идея или хорошая идея, если она у вас есть?

Ссылка удалена.Добавляем основные моменты

Это следует из идеи Project Coin

OVERVIEW
Provide a two sentence or shorter description of these five aspects of the feature:
FEATURE SUMMARY: Should be suitable as a summary in a language tutorial.

Относитесь к массиву как к объектам со своими собственными методами, а не как к значениям, передаваемым вспомогательным методам.Это приводит к более естественному кодированию и делает методы более оперативными.напримерпосредством завершения кода.

MAJOR ADVANTAGE: What makes the proposal a favorable change?

Он переносит объектно-ориентированное программирование на массивы, поддерживая уже доступные и написанные методы.

MAJOR BENEFIT: Why is the platform better if the proposal is adopted?

Объектно-ориентированная согласованность для массивов.

MAJOR DISADVANTAGE: There is always a cost.

Кто-то должен это написать и протестировать.

ALTERNATIVES: Can the benefits and advantages be had some way without a language change?

Вызов вспомогательных методов.

EXAMPLES
Show us the code!
SIMPLE EXAMPLE: Show the simplest possible program utilizing the new feature.

int[] ints = {5,4,3,2,1};
ints.sort(); // instead of Arrays.sort(ints);
int pos = ints.indexOf(5); // instead of Arrays.asList(ints).indexOf(5); or ArraysUtils.indexOf(ints, 5);
ints.reverse(); // instead of Arrays.reverse(ints);
Array array = ints; // cast to super class.
int length = array.getLength(); // instead of Array.getLength(array);
Object n = array.get(3); // instead of Array.get(array, 3);
array.set(3, 7); // instead of Array.
Object obj = array;
System.out.println(obj); // prints [5,4,7,2,1] instead of having to if (obj instanceof int[]) System.out.println(Array.toString((int[]) obj)); else if (....)

РАСШИРЕННЫЙ ПРИМЕР:Покажите расширенное использование функции.

int[] ints = {5,4,3,2,1};
int[] ints2 = ints.copyOf(2);
int[] ints3 = ints.subArray(2,4);
ints.sort(myComparator);
List<Integer> list = ints.asList();
Set<Integer> set = ints.asSet();
long total = ints.sum();
double avg = int.average();
int max = ints.max();
int max2 = ints.max(myComparator);
http://commons.apache.org/lang/api/org/apache/commons/lang/ArrayUtils.html
int[] onemore = ints.add(8); // instead of ArrayUtils.add(ints, 8);
int[] moreInts = ints.addAll(ints2); // instead of ArraysUtils.addAll(ints, ints2);
int[] oneless = int.remove(3); // instead of ArrayUtils.remove(ints, 3);
Integer[] integers = int.toObject();
int[] intsAgain = integers.toPrimitive();

DETAILS
SPECIFICATION: Describe how the proposal affects the grammar, type system, and meaning of expressions and statements in the Java Programming Language as well as any other known impacts.

Такой класс, как java.lang.Array, необходимо будет добавить в качестве родительского элемента для всех массивов.Также могут потребоваться подклассы для конкретных int[], boolean[].Грамматика не должна сильно отличаться.

COMPILATION: How would the feature be compiled to class files? Show how the simple and advanced examples would be compiled. Compilation can be expressed as at least one of a desugaring to existing source constructs and a translation down to bytecode. If a new bytecode is used or the semantics of an existing bytecode are changed, describe those changes, including how they impact verification. Also discuss any new class file attributes that are introduced. Note that there are many downstream tools that consume class files and that they may to be updated to support the proposal!

В предложениях можно использовать нового родителя для массивов, компиляция будет такой же, как сейчас.Однако именно JVM должна будет признать, что массив имеет другой суперкласс.

TESTING: How can the feature be tested?

Убедитесь, что новые методы выполняют то же самое, что и вспомогательные методы.(Должно быть просто, если они действительно вызывают одни и те же вспомогательные методы)

LIBRARY SUPPORT: Are any supporting libraries needed for the feature?

Это следует добавить в rt.jar

REFLECTIVE APIS: Do any of the various and sundry reflection APIs need to be updated? This list of reflective APIs includes but is not limited to core reflection (java.lang.Class and java.lang.reflect.*), javax.lang.model.*, the doclet API, and JPDA.

Суперкласс для массива должен будет возвращать java.lang.Array или что-то подобное вместо java.lang.Object.Однако, опять же, это может быть изменение для JVM, а не для кода rt.jar.

OTHER CHANGES: Do any other parts of the platform need be updated too? Possibilities include but are not limited to JNI, serialization, and output of the javadoc tool.

Это изменение должно быть отражено в файле javadoc.

MIGRATION: Sketch how a code base could be converted, manually or automatically, to use the new feature.

Замените вызовы Arrays.xxx(array, args) на array.xxx(args);

COMPATIBILITY
BREAKING CHANGES: Are any previously valid programs now invalid? If so, list one.

Вызовы hashCode() и Equals() будут изменены, если будут использованы все методы.Это может быть неприемлемо, и в этом случае эти методы можно оставить как есть, а не вызывать Arrays.hashCode() или Arrays.equals();

EXISTING PROGRAMS: How do source and class files of earlier platform versions interact with the feature? Can any new overloadings occur? Can any new overriding occur?

Нет.

REFERENCES
EXISTING BUGS: Please include a list of any existing Sun bug ids related to this proposal.

Это то, по чему мне нужна помощь, отчеты об ошибках или другие ссылки.

Это было полезно?

Решение

Вместо этого я предлагаю вам изучить различные классы коллекций.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top