English 中文(简体)
(s) vs to String () 模式类中的 String ()
原标题:pattern() vs toString() in Pattern class

patrtan () 方法与 toString () 方法在 pater 类中的区别是什么?

医生说:

public String pattern()

返回用于编译此图案的正则表达式。

public String toString()

返回此图案的字符串表示式。这是此图案编译的正则表达式 。

即使是执行也得出了同样的结果:

import java.util.regex.*;

class Test {
  public static void main(String[] args) {
    Pattern p = Pattern.compile("[a-zA-Z]+\.?");
    String s = p.pattern();
    String d = p.toString();
    System.out.println(s);
    System.out.println(d);
  }
}

我看不出有什么区别,为什么有两种方法?还是我漏掉了什么?

最佳回答

Because each class has a toString() method which was inherited from Object. The toString() method is supposed to return a string which represents the object the best way it can, if it is even possible to create some kind of string representation. The name toString() is pretty vague, so they added a method pattern() which is more straightforward.

因为他们想要toString () 返回一些聪明的东西, 他们使用 Regex 的图案, 这是 < code> patern 类的一个很好的字符串表示 。

问题回答

toString () et String () 方法存在于每类中( 类中的扩展点为 < code> Object /code > ) 。 有一个示例。 < code> System.out. 。 < code> system 可以打印一些关于 < code> Object 的信息。 实际上, 这将是一样的 : < code> System.out. priter( o.to String ()) . < code > 。 因此, 您可以简单的方式查看您拥有的对象 。 尝试 :

Object someUnknownObject = new JButton();
System.out.println(someUnknownObject);

// output
javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5...

您可以看到关于此对象的信息, 即使您不知道这是一个按钮。

还有 String Object 所以有一个奇怪的例子:

String str = "hello";
String toStr = str.toString();

System.out.println(str.toString().toString().toString()...);

这是不有用的, 但 所有班级都有这个方法 。 所以“ my string” 和“ my string” 是相同的 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签