EXTENDING the string class

ok, i know extending the string class is illegal because it's final, but i want to make an advanced string class that basically "extends" the string class and i've seen online this can be done through wrapper classes and/or composition, but i'm lost
here is my sample code that is coming up with numerous compile time errors due to the fact that when i declare a new AdvString object, it doesn't inherit the basic string features (note: Add is a method that can add a character to a specified location in a string)
class AdvString
     private String s;
     public AdvString(String s)
          this.s = s;
     public void Add(int pos, char ch)
          int this_len = (this.length()) + 1;
          int i;
          for(i=0;i<(this_len);i++)
               if(pos == i)
                    this = this + ch;
               else if(pos < i)
                    this = this + this.charAt(i-1);
               else
                    this = this + this.charAt(i);
     public static void main(String[] args)
          AdvString s1;
          s1 = new AdvString("hello");
          char c = 'x';
          int i = 3;
          s1.Add(i,c);
          //s2 = Add(s1,i,c);
          //String s2_reversed = Reverse(s2);     
          System.out.println("s1 is: " + s1);
any tips?

see REString at,
http://www.geocities.com/rmlchan/mt.html
you will have to replicate all the String methods you are interested in, and just forward it to the String instance stored in REString or the like. it is like a conduit class and just passes most processing to the 'real' string. maybe a facade pattern.

Similar Messages

  • Extend the String Class

    Is there a way to extend the string class? I know it's final, if i make my class final too would that work? I want to add some functionality to the string class, but I wanna be able to do concatination with the + operator and stuff like that. That's special to the String class.
    Any help would be great.
    Thanks.
    Joe

    Well, put your mind at easy with the fact that being
    able to use the '+' operator on Strings is a design
    flaw in Java. At least from a purist point of view...And from a pragmatist's point of view, it's a reasonable compromise, the benefit of which outweighs the downside. This is consistent with Java's goal as a good general-purpose language. It's not intended to be pure OO or pure anything else.

  • Confused about extending the Sprite class

    Howdy --
    I'm learning object oriented programming with ActionScript and am confused about the Sprite class and OO in general.
    My understanding is that the Sprite class allows you to group a set of objects together so that you can manipulate all of the objects simultaneously.
    I've been exploring the Open Flash Chart code and notice that the main class extends the Sprite class:
    public class Base extends Sprite {
    What does this enable you to do?
    Also, on a related note, how do I draw, say, a line once I've extended it?
    Without extending Sprite I could write:
    var graphContainer:Sprite = new Sprite();
    var newLine:Graphics = graphContainer.graphics;
    And it would work fine. Once I extend the Sprite class, I'm lost. How do I modify that code so that it still draws a line? I tried:
    var newLine:Graphics = this.graphics;
    My understanding is that since I'm extending the Sprite class, I should still be able to call its graphics method (or property? I have no idea). But, it yells at me, saying "1046: Type was not found or was not a compile-time constant: Graphics.

    Thanks -- that helped get rid of the error, I really appreciate it.
    Alas, I am still confused about the extended Sprite class.
    Here's my code so far. I want to draw an x-axis:
    package charts {
        import flash.display.Sprite;
        import flash.display.Graphics;
        public class Chart extends Sprite {
            // Attributes
            public var chartName:String;
            // Constructor
            public function Chart(width:Number, height:Number) {
                this.width = width;
                this.height = height;
            // Methods
            public function render() {
                drawAxis();
            public function drawAxis() {
                var newLine:Graphics = this.graphics;
                newLine.lineStyle(1, 0x000000);
                newLine.moveTo(0, 100);
                newLine.lineTo(100, 100);
    I instantiate Chart by saying var myChart:Chart = new Chart(); then I say myChart.render(); hoping that it will draw the axis, but nothing happens.
    I know I need the addChild method somewhere in here but I can't figure out where or what the parameter is, which goes back to my confusion regarding the extended Sprite class.
    I'll get this eventually =)

  • (Class ? extends Set String ) Class.forName("example.SetImpl").asSubclass

    Is there a way to do the following without an Unchecked cast?
    Class<? extends Set<String>> clazz;
    clazz = (Class<? extends Set<String>>) Class.forName("example.SetImpl").asSubclass(Set.class);
    Set<String> mySet = clazz.newInstance();
    cheers,
    reto

    No. The last line will always generate that warning making the second line pointless. There is no way to create a new instance of a generic class because there is (for most intents and purposes) no such thing as a generic class at runtime.

  • Extending the Thread class

    i would like to do that
    1) One thread displays "ABC" every 2 second;
    2) The other thread displays DEF every 5 seconds;
    i need to create the threads by extending the Thread class ...
    thank you for your help ,
                public class Thread1 extends Thread {
              public Thread1(String s ) {
                   super (s);
              public void run() {
                   for ( int i=0; i<5; i++ ) {
                        System.out.println(getName());
                        try {
                           sleep ((long) 5000);
                        } catch (InterruptedException e ) {
                           /* do nothing */
              public static void main (String args[]) {
                   new Thread1 ("ABC").start();
                   new Thread1 ("DEF").start();
         }     

    I think he has been told to use the Thread class by the sounds of it.
    public class Thread1 extends Thread {
         public Thread1(String s ) {
              super (s);
         public void run() {
              for ( int i=0; i<5; i++ ) {
                   System.out.println(getName());
                   try {
                      sleep (getName().equals("ABC")? 5000 : 2000); //If you don't understand this then Google for "Java ternary operator"
                   } catch (InterruptedException e ) {
                      /* do nothing */
         public static void main (String args[]) {
              new Thread1 ("ABC").start();
              new Thread1 ("DEF").start();
    }

  • Extending the Dialog Class

    Hey, I'm trying to extend the Dialog class into something called a DialogErrorBox, which is just what it sounds like: a dialog box specifically for telling the user about errors it encounters. Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    class DialogErrorBox extends Dialog implements ActionListener {
         public DialogErrorBox (Frame parent) {
        ...//modified to give a vague error message
         }//end constructor
    public DialogErrorBox (Frame parent, String title, String message) {
        ...//worked as a function in my program
         }//end constructor
    public void actionPerformed (ActionEvent evt) {
              this.dispose();
    }The compiling error I recieve at both constructors is:
    ...cannot resolve symbol
    symbol  : constructor Dialog  ()
    location: class java.awt.Dialog
            public DialogErrorBox2 (Frame parent, String title, String message) {I can't figure out why this error would happen. I've made a class extending Frame(Frame and Dialog both extend Window) that looks almost exactly the same and it has no errors.
    Help would be much appreciated.

A: Extending the Dialog Class

This is a short and spotty explanation, to get the full skinny you might read pages 69 and 70 of The Java Programming Language 3rd Edition, Gosling, et. al.
If you don't use the superclass's constructor or one your own as the first executable statement , the superclass's no arg constructor gets called. This means that super() will get called automagically! I don't believe that Dialog has a no arg constructor, so you are forced to do something.
You could also do something like this:
public DialogErrorBox(Frame frame, String title) {
   this(frame, title, true);
}Now the two argument constructor invokes the three arument constructor with a default value of true.
Do you see why this must happen?

This is a short and spotty explanation, to get the full skinny you might read pages 69 and 70 of The Java Programming Language 3rd Edition, Gosling, et. al.
If you don't use the superclass's constructor or one your own as the first executable statement , the superclass's no arg constructor gets called. This means that super() will get called automagically! I don't believe that Dialog has a no arg constructor, so you are forced to do something.
You could also do something like this:
public DialogErrorBox(Frame frame, String title) {
   this(frame, title, true);
}Now the two argument constructor invokes the three arument constructor with a default value of true.
Do you see why this must happen?

  • How to implement the String class "split()" method (JDK1.4) in JDK 1.3

    is it possible , with some code, to implement the split() method of the String class......which is added in JDK1.4 ..... in JDK1.3
    would be helpful if anyone could suggest some code for this...

    Here it is
    public static String[] split(String source, char separ){
    answer=new Vector();
    int position=-1, newPosition;
    while ((newPosition=source.indexOf(separ,position+1))>=0){
    answer.add(source.subString(position+1,newPosition));
    position=newPosition;
    } //while
    answer.add(source.subString(position+1,source.length-1);
    return (String[])(answer.toArray());
    } //split

  • What does the trim() method of the String class do in special cases?

    Looking here ( String (Java Platform SE 7 ) ), I understand that the trim() method of the String class "returns a copy of the string, with leading and trailing whitespace omitted", but I don't understand what the last special case involving Unicode characters is exactly.
    Looking here ( List of Unicode characters - Wikipedia, the free encyclopedia ), I see that U+0020 is a space character, and I also see the characters that follow the space character (such as the exclamation mark character).
    So, I decided to write a small code sample to try and replicate the behaviour that I quoted (from the API documentation of the trim method) in the multi-line comment of this same code sample. Here is the code sample.:
    public class TrimTester {
        public static void main(String[] args) {
             * "Otherwise, let k be the index of the first character in the string whose code
             * is greater than '\u0020', and let m be the index of the last character in the
             * string whose code is greater than '\u0020'. A new String object is created,
             * representing the substring of this string that begins with the character at
             * index k and ends with the character at index m-that is, the result of
             * this.substring(k, m+1)."
            String str = "aa!Hello$bb";
            System.out.println(str.trim());
    However, what is printed is "aa!Hello$bb" (without the quotes) instead of "!Hello$" (without the quotes).
    Any input to help me better understand what is going on would be greatly appreciated!

    That's not what I was thinking; I was thinking about the special case where the are characters in the String whose Unicode codes are greater than \u0020.
    In other words, I was trying to trigger what the following quote talks about.:
    Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).
    Basically, shouldn't the String returned be the String that is returned by the String class' substring(3,9+1) method (because the '!' and '$' characters have a Unicode code greater than \u0020)?
    It seems to not be the case, but why?

  • Can we extend the Throwable class instead of Exception Class??

    Hi all..
    Can we extend the Throwable class instead of Exception Class while creating our own custom Exception?If not Why?
    Please give your valuble advices..
    Ramesh.

    I don't want to hijack the thread here, but in a conversational tone...on a related note.. I've thought about this too a bit and wondered if there are some recommended practices about catching and handling Throwable in certain applications. Like the other day I was debugging a web application that was triggering a 500. The only way I could find the problem in an error stack was to write code to catch Throwable, log the stack, and then re-throw it. I considered it "debug" code, and once I solved the problem I took the code out because, my understanding is, we don't want to be handling runtime problems... or do we? Should I have a catch clause for Throwable in my servlet and then pass the message to ServletException?
    So along with the OP question, are there separate defined occasions when we should or should not handle Throwable? Or does it just all depend on circumstance?

  • How can I extend the Vector class?

    Hi All,
    I'm trying to extend the Vector class so I can get add a .remove(item:T) method to the class.  I've tried this:
    public class VectorCollection extends Vector.<T>
    That gives me the compile error "1017: The definition of base class Vector was not found"
    So then I tried:
    public class VectorCollection extends Vector
    Which gives me the compile error "1016: Base class is final."
    There must be some way to extend the Vector class, though, as on the Vector's official docs page it says:
    Note: To override this method in a subclass of Vector, use ...args for the parameters, as this example shows:
         public override function splice(...args) {
           // your statements here
    So there must be a way to extend the Vector class.  What am I doing wrong?

    No. AS3 doesn't currently have full support for generic types; Vector.<T> was added in an ad-hoc ("ad-hack"?) way. We are considering adding full support in a future version of ActionScript.
    Gordon Smith
    Adobe Flex SDK Team

  • Question about the String class

    Did I understood the JLS/Javadoc properly if I say that the String class has got an internal pool of String objects (therefore I expect this pool to be stored in some sort of static variable)?
    Looking at the intern() method in the String class, this is declared as native, which make me think the whole pooling thing is managed internally by the JVM.
    Does this mean that, if there is only a String class per JVM and String literals (or better Strings that are values of constant expressions) are pooled in the String class, the more String constants are around the bigger the String class object becomes?

    Did I understood the JLS/Javadoc properly if I say
    that the String class has got an internal pool of
    String objects (therefore I expect this pool to be
    stored in some sort of static variable)?Yes.
    Looking at the intern() method in the String class,
    this is declared as native, which make me think the
    whole pooling thing is managed internally by the JVM.The intern() method is implemented in some programming language. If you happen to have a Java runtime where it is written as a native method, it is probably implemented in C or C++. Not a terribly important detail.
    Does this mean that, if there is only a String class
    per JVM and String literals (or better Strings that
    are values of constant expressions) are pooled in the
    String class, the more String constants are around
    the bigger the String class object becomes?The String.class object (of type java.lang.Class) as such doesn't "grow", but some memory structure somewhere will contain interned String literals. Probably a hash table of some sort. Yes indeed: if you have String literals in your program, those literals are stored in the computer's memory during runtime so that they can be accessed by the executable program code.

  • Explicitly extending the Object class

    Hi Everyone,
    I am aware that every object that is running inside a JVM inherits from class Object implicitly. Recently I have come across some code that explicitly extends the Object class, is there any advantage in doing this, please see the code snippet below:
    public class MyClass extends Object{}Thanks heaps for your assistance.
    Regards
    Davo

    I've even seen a
    method that was declared "throws NullPointerException"shouldn't it have been "throws java.lang.NullPointerException" ...
    - I almost cried. Yes, thats truly a terrible habit :(
    a distant cousin of that habit is one I have noticed where the developer
    is totally unable to name anything appropriately..
    to print some things to the screen: "loadData"
    to print things to screen again: "getInformation" *(note: did not 'return' anything).
    ... :(

  • The String class depracated?

    I am porting our application to Solaris 10, Oracle 11, yada, yeda.
    Anyway, our long written code used the GNU C++ Class Library - the String class. It appears that the String class does not exist in the latest distribution (4.2).
    Can anyone verify if that is true or if I am mistaken?
    If this is true, I will have to implement the functionality I need in the class that we have built on top of the Sting class.
    Some of the functionality of that class I need fcompare, before, after, gsub and freq.
    Thanks

    Upon further research, it is the String class from libg++ that is no longer included.
    I am currently trying to compile the older version of this library, but having many issues using the newer compilers.

  • How does the String class achieve this.

    How come we can do the following with the String class:
    // The class is initialized using the equals sign!
    String s = "Hello, World"";I am currently checking the string class but can not find what makes the above possible. could anyone help me?

    ok sorry for not being so clear :)
    When having a String class, we can initialize it by doing the following:
    String myString = "Hello World"; Whis as JosAH explained it is handeled by the compiler. However my common sense tells me that the String class is nothing but a normal class (not like int, long, etc). So if it a normal class, then in that class there is a way to understand what = "somthing" means, and update it's state accordingly.
    I would like to do the same think with my class. example:
    Person MyPerson = "John, Smith";The above is a stupid example, however it gathers my point. The String class sess what is inside the quates and updates it state (with the help of the compiler). Can the Person class do the same? how?

  • I need help extending the MovieClip class

    I want to add a property to the MovieClip class. I just have a bunch of MovieClips that are placed on the stage by reading an XML file and creating lots of clips according to the information in them. Now, I need to know which MovieClips were created below previous clips, and I figure that the easiest way to do so would be by extending the MovieClip class and add an order property.
    I have some problems though: I don't know how to set or get this order property within the main clip, I don't know how to place this clip within my movie, and I don't know how to create them dynamically (do I just do something like var myNewObjectOfExtendedClass : myExtendedClassName = new myExtendedClassName?)
    This is the code I have on my extended class, called Expando.as:
    class Expando extends MovieClip {
    private var _order:Number;
    public function get order():Number {
    return _order;
    public function set order(nOrder:Number):Void {
    _order = nOrder;

    You mean the Tree component?
    My concern with the Tree component (at least the AS2 version) is that I don't see a way to have each node in the Tree have different hit areas with different outcomes.
    The tree that I build must have up to 7 levels within each main branch, and not all of them behave the same way. In some branches, clicking the icon next to the label will have a completely different outcome than clicking on the label, which may or may not return a function. Each of those sublevels also need to support different icons, depending on what information is represented by it.
    Sample:
    • Reminders
    My Reminders
    Manual Reminders
    Escalated Reminders
    • Cases
    Name Actions < ---- this is where the problem begins. Clicking on the icon where the bullet should be should do something different than clicking on the name, which should do something different than clicking on the word ActionsThis is information about that referral that includes who referred them, the date of the referral, their full address. This information usually takes up 2 lines, sometimes 3
    Assignment   <------- you can only open see these leaves if you click on the bullet icon for the previous node; you can't open this by clicking on the text.
    Eligibility
    Etc., depending on what information has been appended
    • Suppliers
    Anyway, if the Tree Component can indeed support these features, I'd like to know where to find information about it please
    In my search for that information, I concluded that I'd probably be better served by building my own MovieClip that can handle these requirements. I did have a working Tree component pretty quickly as I started this project, but then I got more familiar with the app that I'm building the training for and noticed these requirements.
    Of course, maybe all these features are supported by the AS3 Tree component. The problem is that I'm a lot worse with AS3 than I am with AS2 heh.

  • Maybe you are looking for