Computer scienceProgramming languagesJavaCode organizationObject-oriented programmingClass hierarchiesInterfaces and abstract classes

Fundamentals of interfaces in Java

Compact strings with AsciiCharSequence

Report a typo

Wow! This problem is kind of tricky. If you're ready to put your thinking cap on, brace yourself and good luck! Otherwise, you can skip it for now and return any time later

Strings in Java implement the java.lang.CharSequence interface. Since Java internally uses UTF-16, 2 bytes are required to store each char. At the same time, ASCII encoding allows storing character codes in one byte and includes all Latin letters, digits, and standard special characters. Compared to the standard String class, ASCII-character sequences require half the memory.

Write a class named AsciiCharSequence for storing ASCII-character sequences, that should:

  • implement the interface java.lang.CharSequence;

  • have a constructor that takes a byte array;

  • have methods int length(), char charAt(int idx), CharSequence subSequence(int from, int to), and String toString().

You can find the declaration of methods and their behavior in the description of java.lang.CharSequence (JavaDoc or sources).

Carefully check the signatures of the abstract methods of the java.lang.CharSequence interface, especially of the subSequence method. It accepts 2 integers: start index (inclusive) and end index (exclusive). The method returns an object of a class that implements the java.lang.CharSequence interface. In this example it will be an instance of the AsciiCharSequence class.

Note: the testing system will always pass correct input parameters to overridden methods.

Write a program in Java 17
import java.util.*;

class AsciiCharSequence /* extends/implements */ {
// implementation
}
___

Create a free account to access the full topic